In a financial monitoring system, given an array of non-negative integers transactions (each element is the net transaction value for a day) and a positive integer k, find the length of the longest contiguous subarray whose sum is divisible by k. Return 0 if no such subarray exists.
Constraints
- 1 ≤
transactions.length≤ 10⁵ - 0 ≤
transactions[i]≤ 10⁹ - 1 ≤
k≤ 10⁹
解法
前缀和模 k。两个余数相同的前缀和之间的子数组和能被 k 整除。记录每个余数首次出现的下标,对每个 i 更新 ans = max(ans, i - first_idx[prefix_mod])。用 first_idx[0] = -1 初始化,让前缀本身可被算上。复杂度 O(n)。
solution([2, 3, 1, 6, 1, 5], 3) = 6
solution([1], 3) = 0
solution([1, 2, 3, 4, 5], 3) = 5
solution([2, 7, 6, 1, 4, 5], 3) = 4
def solution(transactions: list[int], k: int) -> int:
# first_idx[r] = first prefix index where residue r appeared
first_idx = {0: -1}
prefix_mod = 0
ans = 0
for i, x in enumerate(transactions):
prefix_mod = (prefix_mod + x) % k
if prefix_mod in first_idx:
ans = max(ans, i - first_idx[prefix_mod])
else:
first_idx[prefix_mod] = i # only record first occurrence -> longest span
return ansimport java.util.HashMap;
class Solution {
int solution(int[] transactions, int k) {
HashMap<Long, Integer> firstIdx = new HashMap<>();
firstIdx.put(0L, -1); // empty prefix has residue 0
long prefixMod = 0;
int ans = 0;
for (int i = 0; i < transactions.length; i++) {
prefixMod = (prefixMod + transactions[i]) % k;
if (firstIdx.containsKey(prefixMod)) {
ans = Math.max(ans, i - firstIdx.get(prefixMod));
} else {
firstIdx.put(prefixMod, i);
}
}
return ans;
}
}#include <unordered_map>
class Solution {
public:
int solution(vector<int>& transactions, int k) {
unordered_map<long long, int> firstIdx;
firstIdx[0] = -1; // empty prefix
long long prefixMod = 0;
int ans = 0;
for (int i = 0; i < (int)transactions.size(); i++) {
prefixMod = (prefixMod + transactions[i]) % k;
auto it = firstIdx.find(prefixMod);
if (it != firstIdx.end()) {
ans = max(ans, i - it->second);
} else {
firstIdx[prefixMod] = i;
}
}
return ans;
}
};Process a sequence of operations on a number line. Each operation is one of:
[1, x]— place an obstacle at coordinatex.[2, x, size]— attempt to place a block of lengthsizewith its right end atx(covering the half-open segment[x - size, x)). Append'1'to the result if the segment contains no obstacle (success), otherwise append'0'.
Return the concatenated result string.
Constraints
- 1 ≤
operations.length≤ 10⁵
operations = [[1, 2],
[1, 5],
[2, 5, 2],
[2, 6, 3],
[2, 2, 1],
[2, 3, 2]]
solution(operations) = "1010"
解法
用有序集合存障碍坐标。放置查询 [2, x, size] 二分找 ≥ x - size 的最小障碍;若存在且 < x 则与障碍相交输出 '0',否则输出 '1'。复杂度 O((I + Q) log I),I 为障碍数。
from sortedcontainers import SortedList
def solution(operations: list[list[int]]) -> str:
obstacles = SortedList()
out = []
for op in operations:
if op[0] == 1:
obstacles.add(op[1]) # O(log n) insert
else:
x, size = op[1], op[2]
l, r = x - size, x - 1 # query closed interval [l, r]
idx = obstacles.bisect_left(l) # first obstacle index >= l
if idx < len(obstacles) and obstacles[idx] <= r:
out.append('0')
else:
out.append('1')
return ''.join(out)import java.util.TreeSet;
class Solution {
String solution(int[][] operations) {
TreeSet<Integer> obstacles = new TreeSet<>();
StringBuilder sb = new StringBuilder();
for (int[] op : operations) {
if (op[0] == 1) {
obstacles.add(op[1]);
} else {
int x = op[1], size = op[2];
int l = x - size, r = x - 1;
Integer ceil = obstacles.ceiling(l);
if (ceil != null && ceil <= r) {
sb.append('0');
} else {
sb.append('1');
}
}
}
return sb.toString();
}
}#include <set>
#include <string>
class Solution {
public:
string solution(vector<vector<int>>& operations) {
set<int> obstacles;
string out;
for (auto& op : operations) {
if (op[0] == 1) {
obstacles.insert(op[1]);
} else {
int x = op[1], size = op[2];
int l = x - size, r = x - 1;
auto it = obstacles.lower_bound(l);
if (it != obstacles.end() && *it <= r) {
out.push_back('0');
} else {
out.push_back('1');
}
}
}
return out;
}
};Given a recording of typed characters, count the number of times the underlying letter changes between consecutive characters (case-insensitive). In other words, lowercase the entire sequence and count adjacent positions where recording[i] differs from recording[i-1].
Constraints
- 1 ≤
recording.length≤ 1000
solution(['W', 'w', 'a', 'A', 'b', 'b']) = 2
solution(['w', 'W', 'a', 'W', 'a']) = 3
解法
单次遍历:每字符转小写,与上一个不同就计数加 1。复杂度 O(n)。
def solution(recording: list[str]) -> int:
if len(recording) <= 1:
return 0
count = 0
prev = recording[0].lower()
for i in range(1, len(recording)):
cur = recording[i].lower()
if cur != prev:
count += 1
prev = cur
return countclass Solution {
int solution(char[] recording) {
if (recording.length <= 1) return 0;
int count = 0;
char prev = Character.toLowerCase(recording[0]);
for (int i = 1; i < recording.length; i++) {
char cur = Character.toLowerCase(recording[i]);
if (cur != prev) {
count++;
prev = cur;
}
}
return count;
}
}#include <cctype>
class Solution {
public:
int solution(vector<char>& recording) {
if (recording.size() <= 1) return 0;
int count = 0;
char prev = tolower(recording[0]);
for (size_t i = 1; i < recording.size(); i++) {
char cur = tolower(recording[i]);
if (cur != prev) {
count++;
prev = cur;
}
}
return count;
}
};Given rates[i] (the value on day i) and strategy[i] ∈ {-1, 0, 1} (sell / hold / buy), the base profit is sum(strategy[i] * rates[i]). You may modify the strategy in exactly one contiguous window of length k (where k is even): within that window the first half is held (0) and the second half is all sold (-1, contributing +rates[i]). Find the maximum total profit achievable.
Constraints
- 1 ≤
rates.length = strategy.length = n≤ 10⁵ - 1 ≤
rates[i]≤ 10⁹ strategy[i] ∈ {-1, 0, 1}kis a positive even integer withk ≤ n
rates = [2, 4, 1, 5, 10, 6]
strategy = [-1, 1, 0, 1, -1, 0]
k = 4
solution(rates, strategy, k) = 18
You start with a list of resources, each labeled "A" or "P". Each cycle proceeds in priority order:
- If you have at least
conversionRatePs, consume that manyPs to produce one extraA. - Otherwise, if you have any
A, consume oneA. - Otherwise, terminate (no further cycle counted).
Return the total number of cycles performed.
Constraints
- 2 ≤
resources.length≤ 500 - 2 ≤
conversionRate≤ 500
solution(["A", "A", "A", "P", "P", "P"], 2) = 13
solution(["A", "A"], 2) = 4
solution(["P", "P", "P"], 3) = 2
Given a list of paragraphs (each paragraph is a list of words) and a line width, render the text as a single boxed block:
- The block is surrounded by a border of
*s, with one space of padding inside the border (*<space>...content...<space>*). - Each non-last line of a paragraph is fully justified to
width: distribute extra spaces evenly between gaps; if they do not divide evenly, the leftmost gaps get one extra space each. - The last line of each paragraph is centered within
width(extra space goes to the right if uneven). - A single-word line is centered (extra space to the right).
- Different paragraphs are concatenated; no blank line between them.
Constraints
- 1 ≤
paragraphs.length≤ 20 - 1 ≤
paragraphs[i].length≤ 10 - 1 ≤
paragraphs[i][j].length≤ width - 5 ≤
width≤ 50
paragraphs = [["Hello", "world"],
["How", "areYou", "doing"],
["Please", "look", "and", "align", "to", "the", "center"]]
width = 16
Output:
[
"********************",
"* Hello world *",
"* How areYou doing *",
"* Please look and *",
"* align to the *",
"* center *",
"********************"
]
Given an array structures[i] of building heights, you may only increase any height by 1 in one operation. A valid final configuration is a perfect arithmetic stepwise pattern: either ascending [c, c+1, c+2, ..., c+n-1] or descending [c, c-1, c-2, ..., c-(n-1)] for some integer c. Return the minimum total operations to reach either pattern.
Constraints
- 2 ≤
structures.length≤ 10⁵ - 1 ≤
structures[i]≤ 10⁹
solution([1, 4, 3, 2]) = 4
solution([5, 7, 9, 4, 11]) = 9
Given a lowercase string text, count the number of contiguous substrings of length 3 that contain exactly two vowels (vowels are a, e, i, o, u).
Constraints
- 0 ≤
text.length≤ 1000
solution("welcome") = 2
solution("") = 0
solution("banana") = 2
You have n batteries. Battery i lasts capacity[i] units and, after being fully drained, needs recharge[i] units to be ready again. You must keep a phone running for t units, swapping batteries instantly when one runs out. Multiple batteries can recharge in parallel. Return the number of batteries you can fully drain within the t units.
Constraints
- 1 ≤
t≤ 5000 - 1 ≤
capacity.length≤ 100 - 1 ≤
capacity[i],recharge[i]≤ 100 recharge.length == capacity.length
solution(t = 8, capacity = [5, 5], recharge = [7, 8]) = 2
Given an array of positive integers fragments and a target accessCode (also a positive integer), count the number of ordered pairs of distinct indices (i, j) (with i ≠ j) such that the decimal string concatenation str(fragments[i]) + str(fragments[j]) equals str(accessCode).
Constraints
- 2 ≤
fragments.length≤ 3 × 10⁴ - 1 ≤
fragments[i]≤ 10⁹
solution([12, 12, 13, 12, 12], 1212) = 12
solution([22, 8, 22, 110], 1108) = 1
solution([777, 7, 777, 77, 77], 7777) = 6
You are given an array of non-negative integers a. Count how many elements of a contain an odd number of occurrences of the digit 0 in their decimal representation.
Example: a = [20, 11, 10, 10070, 7] → solution(a) = 3. The qualifying elements are 20 (one zero), 10 (one zero), 10070 (three zeros). 11 and 7 have zero zeros (even), so they do not count.
Constraints
- 1 ≤
a.length≤ 10³ - 0 ≤
a[i]≤ 10⁹
Given an array of non-negative integers readings, repeatedly replace every element with the sum of its digits until every element is a single digit (the digital root). Then return the most frequent digit in the final array; on a tie return the largest such digit.
Example: readings = [123, 456, 789, 101] → solution(readings) = 6. After reducing: 123 → 6, 456 → 4+5+6 = 15 → 6, 789 → 7+8+9 = 24 → 6, 101 → 2. Final array [6, 6, 6, 2], mode is 6.
Constraints
- 1 ≤
readings.length≤ 100 - 0 ≤
readings[i]≤ 10⁶
Variant of problem 6, but each paragraph gets a per-paragraph alignment flag instead of full justification:
paragraphs[i]is a list of words;aligns[i]is either"LEFT"or"RIGHT";widthis the max characters per line.- Greedily pack words into lines of length ≤
width. Excess whitespace on a line goes to the end whenaligns[i] == "LEFT"and to the front whenaligns[i] == "RIGHT". - Wrap the entire output in a
*border (a top/bottom row ofwidth + 2asterisks, and a*at each end of every line).
Example: paragraphs = [["hello", "world"], ["How", "areYou", "doing"], ["Please look", "and align", "to right"]], aligns = ["LEFT", "RIGHT", "RIGHT"], width = 16.
[
"******************",
"*hello world *",
"*How areYou doing*",
"* Please look*",
"* and align*",
"* to right*",
"******************"
]
Constraints
- 1 ≤
paragraphs.length≤ 50 aligns.length == paragraphs.length- 5 ≤
width≤ 100
A mountaineer studies a line of peaks. Due to an optical illusion, only peaks at least viewingGap positions apart can be compared. Given heights[0..n-1] and viewingGap, return the minimum value of |heights[a] - heights[b]| over all pairs with |a - b| >= viewingGap.
Example 1: heights = [1, 5, 4, 10, 9], viewingGap = 3 → 4. Eligible pairs are (0,3) → 9, (0,4) → 8, (1,4) → 4. Minimum is 4.
Example 2: heights = [3, 10, 5, 8], viewingGap = 1 → 2. With gap 1 all non-adjacent pairs are eligible; pair (1,3) = (10, 8) and (0,2) = (3, 5) both give difference 2.
Constraints
- 2 ≤
heights.length≤ 10⁵ - 1 ≤
heights[i]≤ 10⁹ - 1 ≤
viewingGap < heights.length
A player starts at cell 0 with score 0 on a row of n cells (0..n-1). Cell 0 has value 0. In each move the player can:
- Move +1 cell to the right, or
- Move +p cells to the right, where
pis a prime number whose last digit is 3 (e.g.3,13,23,43, ...).
Landing on a cell adds cell[i] to the score. The game ends at cell n - 1. Return the maximum possible final score.
Example: cell = [0, -10, -20, -30, 50], n = 5. Three reachable strategies:
0 → 3 → 4:-30 + 50 = 200 → 1 → 4:-10 + 50 = 400 → 1 → 2 → 3 → 4:-10 + (-20) + (-30) + 50 = -10
Best is 40.
Constraints
- 1 ≤
n≤ 10⁴ - -10⁴ ≤
cell[i]≤ 10⁴ cell[0] = 0
A disk stores hierarchical data in an unweighted tree of tree_nodes nodes (0..tree_nodes-1), rooted at node 0. Each node i carries a single lowercase character arr[i]. You are given m queries: for each query node q, count the number of ancestors v (including q itself) on the path from q up to the root such that the multiset of characters on the sub-path q → v can be rearranged into a palindrome.
A multiset of characters can form a palindrome iff at most one character has an odd count, i.e. the XOR of the corresponding 26-bit bitmask has at most one bit set (popcount ≤ 1).
Example: tree_nodes = 7, edges [(0,1),(1,2),(2,3),(2,4),(4,5),(4,6)], arr = ['a','b','c','a','c','b','c'], queries = [6, 5, 3]. Answer: [3, 4, 1].
Constraints
- 1 ≤
tree_nodes≤ 10⁵ - 1 ≤
m≤ 10⁵ arr[i]is a lowercase English letter.
Heads up~~ The OP mentioned that the description of this question might not be very accurate or polished as they could barely recall the question now.
A robot whose battery capacity is w, wants to ascend a vertical 2D wall
(N x M). It can start from any cell in the bottom row and wants to reach any
cell in the top row. Each cell can be 'x', meaning the robot can hop on that cell or a '.',
meaning the robot can't hop on that node. However, there are some conditions it has to follow:
It can only move in horizontal (along the same row) or up direction.
The robot currently at (x₁, y₁) can only jump to (x₂, y₂),
if the Euclidean distance between these two cells is less than or equal to w
(robot battery capacity).
Due to some sensor constraints, it can hop at most 2 nodes horizontally (along the same row).
The first line of input is the number of rows, number of columns, and the battery capacity.
The second line is a 2D wall cell graph.
Function Description
Complete the function canAscend in the editor.
canAscend has the following parameter:
String[][] wall: a 2D array representing the wall cells Returns int: the minimum number of hops required to ascend the wall, or -1 if it's not possible
You are given a permutation p of the integers 1 through n.
For each k from 1 to n, determine whether there exists a contiguous subarray whose set of values is exactly {1, 2, ..., k}.
Build a binary string of length n. The k-th character should be '1' if such a subarray exists for that k, otherwise it should be '0'.
Function Description
Complete the function balancedPrefixSetsMask in the editor below.
balancedPrefixSetsMask has the following parameter:
int[] p: a permutation of1..nReturnsString: a binary string whosek-th character indicates whether{1, 2, ..., k}appears as the value set of some contiguous subarray.
Constraints
The source thread did not provide explicit numeric bounds.
pis a permutation of the integers
Example 1
Input:
p = [2, 1, 4, 3]
Output:
"1101"
Explanation:
For k = 1, the subarray [1] works. For k = 2, the subarray [2, 1] works. For k = 3, the values {1, 2, 3} do not occupy a contiguous span. For k = 4, the whole array works.
Example 2
Input:
p = [3, 1, 2, 5, 4]
Output:
"11101"
Explanation:
The sets {1}, {1, 2}, and {1, 2, 3} all appear within contiguous spans. The set {1, 2, 3, 4} does not. The whole array gives {1, 2, 3, 4, 5}.
Given a binary tree where each node stores an integer value, compute three results for the same tree.
- the sum of all node values
- the maximum path sum, where a path may start and end at any nodes and must follow parent-child edges
- one path that achieves the maximum path sum, written as node values from start to end
The tree is encoded with two arrays.
values[i]is the value of nodei.children[i] = [left, right]stores the child indices of nodei, and-1means that child does not exist. Node0is the root. Return aString[]of length 3 containing the total sum, the maximum path sum, and one maximum path as space-separated node values.
Constraints
1 ≤ n ≤ 2 * 10⁵-10⁹ ≤ values[i] ≤ 10⁹- The input forms a valid tree reachable from node
0.
Example 1
Input:
values = [1, 2, 3]
children = [[1, 2], [-1, -1], [-1, -1]]
Output:
["6", "6", "2 1 3"]
Explanation:
The tree sum is 1 + 2 + 3 = 6. The best path is 2 -> 1 -> 3, which also sums to 6.
20Bus Time
Hi! One other question in the same batch is LC1438. Please check out the second source image below for more details :) Once upon a time in a bustling city, there was a bus stop where buses departed throughout the day. The city's transportation department had a neat little list called the "schedule," which recorded all the bus departure times in the order they were set to leave. Each bus left precisely on time, and the townsfolk could rely on this schedule to plan their travels. One day, a traveler stood at the bus stop, eager to know when the last bus had departed. The current time was displayed on a big clock at the stop, showing the hour and minute in a 24-hour format. The traveler wanted to find out how many minutes had passed since the last bus had left. However, if the traveler was so early that no bus had left yet, they needed to know this as well. To solve this mystery, the traveler needed a simple yet effective way to compare the current time with the times listed in the schedule. They knew that if a bus was scheduled to leave at the exact current time, it hadn't left yet, so they didn't count that as "already departed." And so, with the schedule in hand and the current time on the clock, the traveler set out to discover the number of minutes since the last bus had departed, or to determine if no buses had left yet, returning to their journey either informed or still waiting for the day's first bus.
Constraints
N/A
Example 1
Input:
plan = ["12:30","14:00", "19:55"]
slot = "14:30"
Output:
30
Explanation: N/A for now
Uba is introducing a new flight service between n countries with n-1 flight routes connecting them. All flights are bi-directional. The flight network forms a tree. Each country is either classified as Open or Restricted based on their current Covid-19 situation. Uber flights can freely visit any open country but are not allowed to land in or fly from restricted countries. However, it can obtain special permission to convert some restricted to open countries. Due to a hardware malfunction, it can only convert the countries in pairs. Requesting more permissions than the number of restricted countries results in an error. For each country, determine the maximum number of countries that can be visited by Uber flights originating from that country, assuming optimal conversion of restricted to open. Each country obtains special permissions independently. Return the sum of the countries a flight can visit from each country.
Constraints
n ≤ 50005
Example 1
Input:
n = 7
s = "ROROROO"
a = [1, 1, 3, 3, 5, 5]
Output:
33
Explanation: Array of answer for each node: 4, 4, 5, 5, 5, 5, 5. The sum of the countries a flight can visit from each country is 4 + 4 + 5 + 5 + 5 + 5 + 5 = 33.
Note - Feel free to checkout the srce image below for the original statement :) Imagine a magical adventure where you guide a brave character through a series of enchanting levels. The character begins this journey with an initial health value, a precious resource that fluctuates as they encounter various challenges in each level. As you progress through these levels, each experience, whether it's a thrilling battle or a rewarding discovery, influences the character’s health. These changes are captured in an array of integers, deltas, where the value at each level determines how much the character's health increases or decreases. However, there's a twist! If the character's health ever falls below 0, it's lovingly set to 0, ensuring they never completely lose hope. On the other hand, if their health exceeds 100, it gently settles back down to 100, keeping them from becoming too invincible. Your quest is to guide this character through all the levels, and at the end, discover their final health value after all these adventures. The goal isn’t necessarily to find the most cunning solution, but rather one that reliably determines the character's final health without taking too long. So, with that in mind, how will your character's health fare by the end of their journey? Let's find out!
Example 1
Input:
initialHealth = 12
deltas = [-4, -12, 6, 2]
Output:
8
Explanation: Let's walk through the journey step by step: At the start of our adventure, the character begins with a health value of 12. After overcoming the first challenge (0th level), the character's health decreases by 4, bringing it down to 8. The next challenge (1st level) proves tougher, reducing the health by 12. However, since the health can't dip below 0, it gently resets to 0. In the following level (2nd level), our brave character regains some strength, with the health increasing by 6, reaching a value of 6. Finally, after completing the last level (3rd level), the health further improves by 2, bringing the final health value to 8. So, the journey ends with the character's health at a stable 8.
Uber has launched a new circular shuttle service that operates on a fixed route, starting and ending at the same location while collecting passengers from various designated stops.
The service area consists of n pickup locations, numbered from 0 to n-1. These locations are interconnected by roads, each with a uniform travel cost of 1 unit. The road network is defined by n-1 edges, where each edge [ai, bi] represents a bidirectional road connecting locations ai and bi. This configuration forms a connected tree structure of pickup locations.
Passenger demand is represented by an array of size n, where passengers[i] equals 1 if there's a passenger waiting at location i, and 0 otherwise.
The shuttle service operates as follows: The shuttle may begin its route at any pickup location. Two operations are available at each stop:
Passenger Collection (Cost: 0): Collect all passengers within a radius of 2 roads from the current location. The radius represents the maximum number of road segments the shuttle can reach to pick up passengers without additional cost.
Movement (Cost: 1): Travel to any directly connected pickup point, incurring a cost of 1 unit per road segment.
Objective: Determine the minimum total cost required to collect all waiting passengers and return the shuttle to its starting location.
Important Constraints:
Each time a road segment is traversed, it contributes 1 unit to the total cost (meaning a round trip on the same road costs 2 units).
The pickup locations form a valid tree structure (connected and acyclic).
Goal: Find the optimal starting location and route strategy that minimizes the total operational cost.
Note: If you pass a road 2 times, the cost to traverse that road becomes 2.
Function Description
Complete the function minimumShuttleCost in the editor.
minimumShuttleCost has the following parameters:
int[] passengers: A 1D array of integers wherepassengers[i] = 1indicates a passenger at pickup pointi, andpassengers[i] = 0indicates no passenger.int[][] edges: A 2D array of integers whereedges[i] = [ai, bi]indicates a bidirectional road connectingaiandbi. Returnsint: Minimum cost incurred to start at a pickup point and return to the same starting point after collecting all the passengers from the pickup points.
Constraints
1 ≤ n ≤ 3·10⁴passengers.size()equalsn.0 ≤ passengers[i] ≤ 1edges.lengthequalsn-1.edges[i].lengthequals2.- 0 ≤ aᵢ, bᵢ < n
Example 1
Input:
passengers = [1, 0, 0, 0, 0, 1]
edges = [[0,1],[1,2],[2,3],[3,4],[4,5]]
Output:
2
Explanation: The Uber shuttle can follow the below steps to reduce the cost to 2 and collect all 2 passengers: Start at pick-up point 2 Collect the passenger from pick-up point 0 Move to adjacent pick-up point 3 Collect the passenger from pick-up point 5 Move back to adjacent pick-up point 2 Cost is incurred only during movement from pick-up points 2 to 3 and 3 to 2. Total cost = 2.
Example 2
Input:
passengers = [0, 0, 0, 1, 1, 0, 0, 1]
edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[5,6],[5,7]]
Output:
2
Explanation: The Uber shuttle can follow the below steps to reduce the cost to 2 and collect all 3 passengers: Start at pick-up point 0 Collect the passengers from pick-up points 3 and 4 Move to adjacent pick-up point 2 Collect the passenger from pick-up point 7 Move back to adjacent pick-up point 0 Cost is incurred only during movement from pick-up points 0 to 2 and 2 to 0. Total cost = 2.
You are given an array of commands. There are only three possible commands: cmd1, cmd2, and cmd3. Your task is to return an array of size 3 that contains the frequency of each command in the input array, in the order [frequency of cmd1, frequency of cmd2, frequency of cmd3].
Also, any element in the form of ![index] refers to the same command that was present at the position in the input array. Note that indexing starts from 1 (not 0).
Function Description
Complete the function commandFrequencyCounter in the editor.
commandFrequencyCounter has the following parameter:
String[] commands: an array of commands Returnsint[]: an array of size 3 containing the frequency of each command
Example 1
Input:
commands = ["cmd1", "cmd2", "cmd3", "!1", "!2", "cmd3", "cmd1"]
Output:
[3, 2, 2]
Explanation:
At index 4 (!1), the command is the same as the command at index 1 (cmd1).
At index 5 (!2), the command is the same as the command at index 2 (cmd2).
Complete the function below. The function receives the full standard input as a single string and returns the exact standard output lines.
You are given access to a black-box convex or unimodal function on a closed interval [a, b]. In this text version, the black-box function is represented as a quadratic F(x) = ax² + bx + c, and you must find the approximate x in the search interval that minimizes F(x).
For each query, output the minimizing x rounded to exactly six digits after the decimal point. If the unconstrained minimizer lies outside the interval, clamp it to the nearest endpoint.
This models the interview task where the only allowed operation is evaluating the black-box function; ternary search is the intended general approach.
Function Description
Complete solveConvexFunctionMinimization. It has one parameter, String input. The first line is q. Each of the next q lines contains A B C left right for F(x)=A*x*x+B*x+C on interval [left, right]. Return one rounded minimizer per query.
Constraints
Each query describes a convex quadratic with A > 0.
Return answers rounded to exactly six decimal places.
Example 1
Input:
input = "3\n1 -4 7 0 10\n1 2 1 0 5\n2 -8 1 3 10"
Output:
["2.000000","0.000000","3.000000"]
Explanation: The unconstrained minimizers are 2, -1, and 2 respectively; the second and third are clamped to their intervals.
(no statement available)
Constraints
na
Example 1
Input:
nums = [1, 2, 3]
Output:
1
Explanation: Only element 2 satisfies the condition.
Imagine you are an avid gardener planning the layout of a large garden. You have to generate a 2D grid where each cell represents a plot in the garden. You can either plant a flower in a plot or leave it empty. After planting, you want to analyze the garden to find unique arrangements of flowers that form an "L" shape, as these arrangements are aesthetically pleasing and optimize space usage.
A value of 1 in the grid indicates a plot where a flower is planted, and a value of 0 indicates an empty plot.
An "L" shaped flower arrangement is defined as follows:
A collection of 3 plots of a garden is said to be L shaped arrangement if one of its plots is in the same row with another plots and in the same column with the third plots. The 3 plots do not have to be next to each other.
All three plots must contain flowers (value of 1).
Input:
The inputs provided will include "row", "col", "magicNumber", and "mod". "Row" and "Col" specify the size of the grid in terms of rows and columns. To determine the presence of a flower in any cell, we use the formula:
((i+j*magicNumber)%mod)%2
where "i" and "j" refer to the row and column indices, respectively. The indices "i" and "j" start from 0 and go up to row-1 and col-1, respectively. The '%' symbol denotes the modulus operation.
Output:
Return the number of such "L" shaped arrangements in the garden.
Constraints
- 1 ≤ row ≤ 1000
- 1 ≤ col ≤ 1000
- 0 ≤ grid[i][j] ≤ 1
- 1 ≤ mod ≤ 1000000
- 1 ≤ magicNumber ≤ 1000000
At the Robotics Innovation Campus "UBERBOT", Unit IG-0R is a vertical wall-climbing robot that can scale surfaces using embedded magnetic contact points (nodes). The robot is deployed on a vertical metal wall designed as a rectangular grid with:
n horizontal levels (rows)
m segments per level (columns)
Each segment is either:
'X' (node the robot can use)
'#' (empty space)
Valid Route Criteria
Start: The first node must be on the bottommost level (row n).
End: The last node must be on the topmost level (row 1).
Level-by-Level Progression:
The robot may only move upward or horizontally; it cannot move to a lower level. The robot must access at least one node per level to recharge its navigation sensors.
Node Usage per Level:
The robot can use up to two nodes per level (due to sensor synchronization constraints). These nodes can be used in any order, but each node is visited at most once in a route.
Battery Constraint:
IG-0R's battery capacity allows it to jump only between nodes whose Euclidean distance is less than or equal to w, unit range.
The distance between two nodes at positions (i1, j1) and (i2, j2) is computed as:
sqrt((i1 - i2)^2 + (j1 - j2)^2)
The robot cannot transition between nodes if the computed distance exceeds its battery limit w.
w ≥ sqrt((i1 - i2)^2 + (j1 - j2)^2)
Function Description
Complete the function countRoutes in the editor.
countRoutes has the following parameters:
-
char[][] grid: a 2D array of characters representing the grid
-
w: an integer representing the maximum Euclidean distance the robot can jump Returns int: the number of distinct valid routes, computed modulo 998244353
Constraints
- 2 ≤ n ≤ 2000
- 1 ≤ m ≤ 2000
- 1 ≤ w ≤ 2000
- Answer is returned modulo 998244353
Example 1
Input:
grid = [
['X', 'X', '#', 'X'],
['#', 'X', 'X', '#'],
['#', 'X', '#', 'X']
]
w = 1
Output:
2
Explanation:
Given an integer array nums and an integer k, return the number of good subarrays of nums.
A subarray arr is good if there are at least k pairs of indices (i, j) such that i < j and arr[i] == arr[j].
A subarray is a contiguous non-empty sequence of elements within an array.
Constraints
1 ≤ nums.length ≤ 10⁵1 ≤ nums[i], k ≤ 10⁹
Example 1
Input:
nums = [1,1,1,1,1]
k = 10
Output:
1
Explanation:
The only good subarray is the array nums itself.
Example 2
Input:
nums = [3,1,4,3,2,2,4]
k = 2
Output:
4
Explanation: There are 4 different good subarrays:
[3,1,4,3,2,2]that has 2 pairs.[3,1,4,3,2,2,4]that has 3 pairs.[1,4,3,2,2,4]that has 2 pairs.[4,3,2,2,4]that has 2 pairs.
Click the source image button below to view the original problem statement Pls don't hesitate to reach out to us if the source image is broken.. We are all on the discord serva Once upon a time in the land of Algorithmlandia, there were two mystical arrays of integers named a and b. These arrays lived peacefully, each filled with unique numbers. The residents of Algorithmlandia often found themselves puzzled by the secrets these arrays held, so they turned to a wise sage who could process their queries and uncover the hidden truths. One day, the people brought forth an array of queries to the sage. Each query held a special request. Some queries came in the form of a spell: "[0, i, x]" - this spell was cast to enhance the magical power of the b array. The spell added the number x to the current value at the i-th position of b. This transformation often led to interesting changes in the array's magic. Other queries arrived with a different incantation: "[1, x]" - this spell sought to uncover pairs of numbers from a and b that held a special bond. The query requested the sage to count all pairs of indices (i, j) such that the sum of a[i] and b[j] equaled the mystical number x. With each query processed in the given order, the sage carefully recorded the results of the second type of spell. These results were then compiled into an array, reflecting the wisdom and insights gained from the magical arrays a and b. And so, the people of Algorithmlandia marveled at the sage's ability to decipher the secrets of the arrays, their lives enriched by the knowledge revealed through the queries. The story of the arrays and the sage's wisdom was passed down through generations, a testament to the power of understanding and the magic of numbers.
You are given a list of house positions in a district, where each house is located at a distinct position along a straight line. Houses that are next to each other without any gaps between them are considered part of the same segment. Your task is to determine how many segments of consecutive houses remain after removing houses according to a series of queries.
Each query removes a house from the district, and after each removal, you need to calculate the number of segments of consecutive houses that remain.
Input:
houses: A list of integers representing the positions of the houses in the district.
queries: A list of integers representing the positions of the houses to be removed. Each query removes one house from the district.
Output:
For each query, return the number of segments of consecutive houses remaining after the corresponding house is removed.
ᯓᡣ𐭩spike is the G.O.A.T ᨒ ོ
Constraints
- The number of houses,
n, is at most10⁵. - The number of queries,
q, is at most10⁵. - All positions in the house list and queries list are distinct integers.
Example 1
Input:
houses = [1, 2, 3, 6, 7, 9]
queries = [6, 3, 1]
Output:
[3, 2, 2]
Explanation: Note - Example 1's output can potentially be wrong. Answer might be [3,3,3]. Initial Setup: Houses are at positions [1, 2, 3, 6, 7, 9], forming three segments: [1, 2, 3], [6, 7], and [9]. After removing house at position 6: Houses are [1, 2, 3, 7, 9], forming three segments: [1, 2, 3], [7], and [9]. Result = 3. After removing house at position 3: Houses are [1, 2, 7, 9], forming two segments: [1, 2], [7], and [9]. Result = 2. After removing house at position 1: Houses are [2, 7, 9], forming two segments: [2], [7], and [9]. Result = 2. Thus, the output after each query is [3, 2, 2].
Example 2
Input:
houses = [1, 5, 6, 8, 10]
queries = [5, 10, 1]
Output:
[3, 3, 2]
Explanation: Caution - Example 2's output and explanation might be wrong. If you look at inital setup, they say there are 3 segments, but it might actually be 4. Initial Setup: Houses are at positions [1, 5, 6, 8, 10], forming three segments: [1], [5, 6], and [8, 10]. After removing house at position 5: Houses are [1, 6, 8, 10], forming three segments: [1], [6], and [8, 10]. Result = 3. After removing house at position 10: Houses are [1, 6, 8], forming three segments: [1], [6], and [8]. Result = 3. After removing house at position 1: Houses are [6, 8], forming two segments: [6] and [8]. Result = 2. Thus, the output after each query is [3, 3, 2].
Another question about defusing bombs - uber-find-minimum-time-to-defuse-all-bombs
Janet is faced with the task of defusing N bombs, numbered from 1 to N. Each bomb i has a timer and will detonate in Yi seconds. To neutralize bomb i, Janet needs Xi seconds. He must finish defusing each bomb before or exactly when its timer runs out. Importantly, he can only work on one bomb at a time. Knowing this in advance, Janet has asked for your assistance. Your goal is to determine whether it's possible for him to defuse all the bombs in time. If it is, return the minimum total time required to complete the defusals. Otherwise, return -1.
Function Description
Complete the function defuseBombs in the editor.
defuseBombs has the following parameter:
int[][] bombInfo: an array ofintarrays where each subarray contains two elements[Xi, Yi], representing the time taken by Janet to defuse theith bomb and the time by which theith bomb will explode Returns int: the minimum total time required to defuse all bombs if possible, otherwise-1
Constraints
1 ≤ N ≤ 2 × 10⁵
Example 1
Input:
bombInfo = [[2, 4], [1, 9], [1, 8], [4, 9], [3, 12]]
Output:
11
Explanation:
You are given a list of users and a list of ride-share log entries. Each log entry records a timestamp and two users who shared a ride. Once two users share a ride, they are considered connected. Connectivity is transitive: if A is connected to B and B is connected to C, then A is connected to C.
Each log entry is formatted as "timestamp userA userB", where timestamp is an integer. Process the logs in increasing timestamp order and return the earliest timestamp when all users are connected. If the users never all become connected, return -1.
Function Description
Complete the function earliestFullConnection in the editor.
earliestFullConnection has the following parameters:
String users[]: all users in the systemString logs[]: ride-share connection logs Returnsint: the earliest timestamp when all users are connected, or-1if this never happens
Constraints
- Each log entry has the format
"timestamp userA userB". - Logs may be provided out of timestamp order.
- User names in logs are included in
users.
Imagine you're developing a core feature for a ride-sharing service, similar to Uber Pool, where the goal is to efficiently group individual ride requests into compatible batches. The objective is to minimize the total number of vehicles required by maximizing the number of compatible riders grouped into each vehicle, while respecting batch size limits.
Each incoming ride request provides essential details. Your task is to identify and form groups (batches) of rides, with a maximum of 3 rides per batch, that can be served together based on compatibility criteria.
Ride Data Format:
Each ride is represented as a list of three strings:
{"ride_id", "pickup_location", "pickup_time"}
Where:
ride_id : A unique identifier for the ride (e.g., "123", "456"). This will always be a string representing a positive integer.
pickup_location : The specific location where the rider needs to be picked up (e.g., "A", "Downtown Station", "123 Main St"). This will always be a string.
pickup_time : The scheduled pickup time in a 24-hour "HH:MM" format (e.g., "09:30", "14:15").
Compatibility Rules:
Two or more rides are considered compatible and can be grouped into the same batch if, and only if:
Same Pickup Location: They share the exact same pickup_location.
Strict Proximity in Time: The difference between the earliest and the latest pickup_time among all rides in that batch must be within 10 minutes (inclusive). For example, if a batch contains rides at 09:00, 09:05, and 09:10, they are compatible (09:10 - 09:00 = 10 minutes). If a ride at 09:11 is added to a batch starting at 09:00, it would not be compatible (09:11 - 09:00 = 11 minutes).
Batching Constraints:
Maximum 3 Rides per Batch: A batch can contain a maximum of 3 rides. If more than 3 compatible rides are available, they must be split into multiple batches. This means a batch can contain 1, 2, or 3 rides.
Unique Assignment: Each ride can belong to at most one batch. Once a ride is assigned to a batch, it cannot be assigned to another.
Batch Output Format: Each batch should be a sorted list of the ride IDs (as integers) that comprise it.
Output Ordering:
The final list of batches should be ordered based on the earliest original input index of any ride within that batch. For example, if a batch contains rides that were originally at index 0 and index 5 in the input list, and another batch contains rides from index 1 and index 2, the batch containing the ride from index 0 would appear first.
Note: The batches are ordered by the earliest input index: [1,2] (index 0), [3,5] (index 2), [4] (index 3), [6] (index 5).
Your Task:Implement a function that takes the list of ride requests as input and returns the final list of batches according to the rules and output ordering specified above.
Constraints
- The maximum number of rides (N) up to 10000.
- (execution time limit) 0.5 seconds (cpp)
Example 1
Input:
rides = [
["1, Downtown Station, 09:00"],
["2, Downtown Station, 09:05"],
["3, Uptown Plaza, 10:00"],
["4, Downtown Station, 09:12"],
["5, Uptown Plaza, 10:07"],
["6, Airport Terminal, 11:00"]
]
Output:
[[1, 2],[3, 5],[4],[6]]
Explanation: Hi - I modified the input type a bit to make work a bit easier for me while uploading..Thank u for ur understanding. Based on the compatibility rules and the strict 10-minute span: Rides "1" (09:00) and "2" (09:05) for "Downtown Station" are compatible and within 10 minutes (09:05 - 09:00 = 5 minutes). They form a batch [1, 2]. This batch has 2 rides, which is ≤3. Ride "4" (09:12) for "Downtown Station": It's not compatible with a batch of [1, 2] because 09:12 - 09:00 = 12 minutes, which is > 10 minutes. Therefore, Ride "4" cannot join the batch [1, 2] and forms its own single-ride batch [4]. Rides "3" (10:00) and "5" (10:07) for "Uptown Plaza" are compatible (10:07 - 10:00 = 7 minutes ≤10). They form a batch [3, 5]. This batch has 2 rides, which is ≤3. Ride "6" (11:00) for "Airport Terminal" is not compatible with any other ride. It forms its own single-ride batch [6].
Design the assignment behavior for a row of n</c
Constraints
When no seats are occupied yet, assign seat 0.
Example 1
Input:
n = 10
count = 5
Output:
[0,9,4,2,6]
Explanation: The first two assignments take the ends. The third assignment chooses seat 4, which is one of the middle seats farthest from 0 and 9; ties use the smaller index.
Example 2
Input:
n = 3
count = 4
Output:
[0,2,1]
Explanation: Only three seats exist, so only three assignments are returned.
Given two arrays of strictly i
Constraints
n/a
Example 1
Input:
arr1 = [123, 4, 5, 955]
arr2 = [12345, 63, 95, 2]
Output:
3
Explanation: n/a
You are given an array of n magical fruits. The power of the fruit is given in an array a of length n. You are also given an integer k. Your task is to find the maximum length L such that every subarray of length L has the sum of powers strictly less than k.
Input Format
The first line contains two integers n and k — the number of fruits and the maximum allowed power sum. The second line contains n integers — the array a, where a[i] is the power of the i-th fruit.
Output Format
Print a single integer — the maximum value of L.
Constraints
1 ≤ n ≤ 2 * 10⁵1 ≤ a[i] ≤ 10⁹1 ≤ k ≤ 10¹⁸
Example 1
Input:
a = [3, 1, 2, 4]
k = 8
Output:
3
Explanation:
Given 4 arrays wins, draws, scored, conceded of size N these arrays represent the stats of N teams. The array wins[i] represents the number of wins of the i'th team, draws[i] represents the number of draws of the i'th team, scored[i] represents the score of the i'th team, and conceded[i] represents the concede of the i'th team.
For every win, a team is rewarded 3 points and for every draw, a team is rewarded 1 point. The task is to find the highest and second-highest scoring teams. If there is a tie between the points, it will be resolved by taking the difference between scored[i] - conceded[i].
Return the indexes of the teams.
Function Description
Complete the function findTopTwoTeams in the editor.
findTopTwoTeams has the following parameters:
int[] wins: an array of integers representing the number of winsint[] draws: an array of integers representing the number of drawsint[] scored: an array of integers representing the scoresint[] conceded: an array of integers representing the conceded scores Returnsint[]: an array of two integers representing the indexes of the top two teams Hello! Uber assessment comes with 4 coding questions. Here are the other 3 in the same batch -
Example 1
Input:
wins = [1, 2, 3]
draws = [1, 1, 1]
scored = [10, 20, 30]
conceded = [12, 23, 12]
Output:
[2, 1]
Explanation: points for team 0 = 13 + 11 = 4 points for team 1 = 23 + 11 = 7 points for team 2 = 33 + 11 = 10 return {2,1} PPS: if there is a tie between teams points it will be resolved by taking the difference bewteen scored[i] - conceded[i]
Your server receives a stream of IP hit events. Design a data structure that supports two operations:
ADD ip: record one hit fromipFIRST_UNIQUE: return the earliest IP address that has appeared exactly once so far, or an empty string if none exists Process all commands in order and return the outputs produced by theFIRST_UNIQUEcommands. Function Description Complete the functionprocessFirstUniqueIpCommandsin the editor below.processFirstUniqueIpCommandshas the following parameter:String[] commands: the commands to execute ReturnsString[]: the answers for theFIRST_UNIQUEcommands in order.
Constraints
- The total number of events can be as large as
10⁷. - The number of distinct IPs can be as large as
10⁶. - IP strings should be treated as opaque strings; validation is not required.
Example 1
Input:
commands = ["ADD 1.1.1.1", "ADD 2.2.2.2", "ADD 1.1.1.1", "FIRST_UNIQUE"]
Output:
["2.2.2.2"]
Explanation:
2.2.2.2 is the earliest IP that has appeared exactly once after the first three add operations.
Example 2
Input:
commands = ["ADD 1.1.1.1", "ADD 2.2.2.2", "ADD 1.1.1.1", "ADD 3.3.3.3", "FIRST_UNIQUE", "ADD 2.2.2.2", "FIRST_UNIQUE"]
Output:
["2.2.2.2", "3.3.3.3"]
Explanation:
After the second query state change, 2.2.2.2 is no longer unique, so the next earliest unique IP is 3.3.3.3.
You are given process logs in arrival order. Treat each log as a full string entry.
Return the first log entry that appears exactly once in the entire sequence. If no such log exists, return an empty string.
Function Description
Complete the function findFirstUniqueLog in the editor below.
findFirstUniqueLog has the following parameter:
String[] logs: the process logs in arrival order ReturnsString: the first log whose final frequency is exactly one, or""if none exists.
Constraints
1 ≤ logs.length ≤ 10⁶- Each log entry is treated as an entire string and may contain spaces.
- The answer is based on the original order among log entries whose final count is exactly one.
Example 1
Input:
logs = ["A", "B", "A", "C", "B"]
Output:
"C"
Explanation:
A and B each appear twice. C is the first log whose total frequency is exactly one.
Example 2
Input:
logs = ["x", "y", "x", "y"]
Output:
""
Explanation: Every log appears more than once, so there is no unique entry.
Given a String array, return the output array in form where
Example 1
Input:
words = ["cat", "dog", "flower", "bed"]
Output:
["cg", "dr", "fd", "bt"]
Explanation: :)
Given an array arr of length n which is a permutation of 1, 2, ..., n, a number k is called balanced if there exist two indices i and j such that arr[i], arr[i+1], ..., arr[j] is a permutation of 1, 2, ..., k.
Return a binary string of length n, where the character at 0-indexed position k-1 is '1' if k is balanced, and '0' otherwise.
Constraints
1 ≤ n ≤ 10⁵arris a permutation of1, 2, ..., n
Example 1
Input:
arr = [4, 1, 3, 2]
Output:
1011
Explanation: k=1: subarray [1] is a permutation of {1} → balanced.k=2: no contiguous subarray equals {1, 2} → not balanced.k=3: subarray [1, 3, 2] is a permutation of {1, 2, 3} → balanced.k=4: full array [4, 1, 3, 2] is a permutation of {1, 2, 3, 4} → balanced.
Example 2
Input:
arr = [1, 2, 3]
Output:
111
Explanation: For every k from 1 to 3, the prefix arr[0..k-1] is already a permutation of {1, ..., k}.
Example 3
Input:
arr = [2, 3, 1]
Output:
101
Explanation: k=1: subarray [1] exists → balanced.k=2: no contiguous subarray is exactly {1, 2} — elements 1 and 2 are separated by 3 → not balanced.k=3: full array [2, 3, 1] is a permutation of {1, 2, 3} → balanced.
Example 4
Input:
arr = [1]
Output:
1
You are given an undirected graph rooted at node 0 with n nodes (numbered 0 to n-1). Each node i is labelled with a lowercase English letter given by labels[i].
You are also given m queries. For each query [node_from, node_to], collect all characters encountered while travelling from node_from to node_to along the unique path in the tree. Determine whether those characters can be rearranged to form a palindrome.
Return a boolean array of length m where result[i] is true if the characters for query i can form a palindrome, and false otherwise.
Constraints
1 ≤ n ≤ 10⁵1 ≤ m ≤ 10⁵labelscontains only lowercase English letters- Edges form a valid tree rooted at node
0
Example 1
Input:
n = 3
labels = "aba"
edges = [[0, 1], [1, 2]]
queries = [[0, 2], [0, 1]]
Output:
[true, false]
Explanation:
Query [0,2]: path is 0→1→2, chars = {a, b, a} → {a:2, b:1} → one odd-count char → can form palindrome → true.Query [0,1]: path is 0→1, chars = {a, b} → {a:1, b:1} → two odd-count chars → cannot form palindrome → false.
Example 2
Input:
n = 2
labels = "aa"
edges = [[0, 1]]
queries = [[0, 1]]
Output:
[true]
Explanation:
Path 0→1 yields {a, a} → {a:2} → zero odd-count chars → true.
Example 3
Input:
n = 4
labels = "abcd"
edges = [[0, 1], [0, 2], [0, 3]]
queries = [[1, 2]]
Output:
[false]
Explanation:
Path 1→2 goes through node 0: chars = {b, a, c} → {a:1, b:1, c:1} → three odd-count chars → cannot form palindrome → false.
You are given an integer array nums. You start at index 0 and want to reach index n - 1.
From index i, you may jump to any later index j if the step length j - i is prime and j - i ≤ nums[i].
Return 1 if the last index is reachable, otherwise return 0.
Function Description
Complete the function canReachWithPrimeSteps in the editor below.
canReachWithPrimeSteps has the following parameter:
int[] nums: the maximum jump lengths Returnsint:1if the end is reachable, otherwise0.
Constraints
1 ≤ nums.length ≤ 2 * 10⁵0 ≤ nums[i] ≤ 10⁹
Example 1
Input:
nums = [2, 3, 1, 1, 0]
Output:
1
Explanation:
Jump from index 0 to 2 using prime step length 2, then from 2 to 4.
Example 2
Input:
nums = [1, 1, 1, 1]
Output:
0
Explanation:
Every allowed jump length is at most 1, and 1 is not prime.
Note - Checkout the source image below for the original prompt :) Imagine you're given a list of numbers and a special pattern that describes how these numbers should relate to each other in a sequence—whether they rise, fall, or stay the same. Your task is to find how many smaller sequences within the list match this pattern exactly. Even though you don't need to find the most efficient way, your solution should be good enough to handle a reasonable amount of work without slowing down too much.
Example 1
Input:
numbers = [4, 1, 3, 4, 4, 5, 5, 1]
pattern = [1, 0, -1]
Output:
1
Explanation: Note - Checkout the source image below for the original explanation :)
Imagine you have a square matrix of numbers, and you're given a set of instructions, called queries, to transform this matrix in different ways. Depending on the query, you might rotate the matrix 90 degrees clockwise, reflect it along its main diagonal, or reflect it along its secondary diagonal. Your task is to apply all these transformations in the order given and return the matrix after it's been beautifully transformed by each of the queries. Don't worry about finding the most efficient way to do this; just ensure your approach isn't too slow for the given task.
Example 1
Input:
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
q = [0, 1, 2]
Output:
[[3, 6, 9], [2, 5, 8], [1, 4, 7]]
Explanation:
An explanation based on educated guess. Might be right might be wrong tho..
After processing the queries on matrix a:
- First query is
0, so we rotate the matrix 90 degrees clockwise. - Second query is
1, so we reflect the rotated matrix in its main diagonal. - Third query is
2, so we reflect the matrix in its secondary diagonal. The final matrix after all transformations is[[3, 6, 9], [2, 5, 8], [1, 4, 7]].
There are n riders and one car with infinite capacity. Each rider i is comfortable riding in the car only if the number of other riders also in the car is between comfort[i][0] and comfort[i][1] (inclusive). If this condition is not met, the rider will not enter the car.
All riders decide simultaneously — a valid group is a subset of riders where every rider in the group is comfortable with the group size minus one.
Return the maximum number of riders that can be in the car at the same time.
Constraints
1 ≤ n ≤ 10⁵0 ≤ comfort[i][0] ≤ comfort[i][1] ≤ n
Example 1
Input:
comfort = [[1, 3], [2, 4], [0, 2], [1, 3]]
Output:
3
Explanation: With k=3 riders, each needs to be comfortable with 2 others. Riders 0 (1–3), 1 (2–4), and 2 (0–2) all include 2 in their range → valid group of 3.With k=4, each would need 3 others. Only riders 0, 1, and 3 cover 3 — only 3 riders qualify, not 4.
Example 2
Input:
comfort = [[0, 2], [0, 2], [0, 2]]
Output:
3
Explanation: With all 3 riders, each is comfortable with 2 others (2 ∈ [0, 2]). All 3 can ride together.
Example 3
Input:
comfort = [[2, 3], [2, 3]]
Output:
0
Explanation: k=1 requires 0 others; k=2 requires 1 other. Neither 0 nor 1 falls in [2, 3] for any rider, so no valid group exists.
Example 4
Input:
comfort = [[0, 0]]
Output:
1
Explanation: The single rider is comfortable with 0 others. They ride alone.
Complete the function below. The function receives the full standard input as a single string and must return the exact standard output lines for the described problem.
Given an m x n matrix of characters '0' and '1', find the largest square containing only '1's and return its area.
Input
First line: two integers m n
Next m lines: each is a length-n string containing only 0/1
Output
A single integer: the maximal square area
Constraints
1 ≤ m, n ≤ 300
Examples
4 5
10100
10111
11111
10010
Output:
4
2 2
00
Output:
0
Example
Input
4 5
10100
10111
11111
10010
Output
4
Function Description
Complete solveMaximalSquareArea. It has one parameter, String input, containing the full stdin payload. Return the stdout payload as an array of lines, without trailing newline characters.
Constraints
Use the limits and requirements stated in the prompt.
Example 1
Input:
input = "4 5\n10100\n10111\n11111\n10010"
Output:
["4"]
Explanation: The returned string array must match the expected standard output lines for the sample input.
There is a magical forest with N trees, each tree i (0 Input:
The first line of input is the number of trees and the value of K. The second line consists of N space-separated values denoting the number of fruits on each tree.
Output:
The maximum value of L
Example 1
Input:
fruits = [3, 1, 2, 4]
k = 8
Output:
3
Explanation: :)
Given array arr of length n, we define function f(arr) as- if n=1, f(arr) = arr[0]; else, f(arr) = f(arr[0] ^ arr[1], arr[1] ^ arr[2],..., arr[n-2] ^ arr[n-1])
where ^ is bitwise XOR operator.
For example, arr = [1, 2, 4, 8], n = 4
f(1, 2, 4, 8) = f(1², 2⁴, 4⁸) = f(3,6,12) = f(3⁶,6¹²) = f(5, 10) = f(5¹⁰) = f(15) = 15.
You need to answer q queries, each query you are given two integers l and r. For each query, what is the maximum of f() for all continuous subsegments of the array from l to r.
Function Description
Complete the function maximumXORForEachQuery in the editor.
maximumXORForEachQuery has the following parameters:
-
int arr[]: an array of integers
-
int l: an integer representing the left index of the range
-
int r: an integer representing the right index of the range Returnsint: the maximum XOR value for all continuous subsegments of the array fromltor
Constraints
N/A
You are given a directed version of a tree with n nodes labeled from 0 to n - 1. Each undirected edge of the tree appears once in the input as a directed edge u -> v.
You may choose any node as the root. After choosing the root, every edge should point away from that root. You may reverse edges, and each reversed edge costs 1.
Return the minimum number of edge reversals needed over all possible root choices.
Function Description
Complete the function minEdgeReversalsForRoot in the editor below.
minEdgeReversalsForRoot has the following parameters:
int n: the number of nodesint[][] edges: directed edges whereedges[i] = [u, v]means the current direction isu -> vReturnsint: the minimum number of reversals required.
Constraints
The source thread did not provide explicit numeric bounds.
- The underlying undirected graph formed by
edgesis a tree. edges.length = n - 1.- Each input edge gives the current direction of exactly one tree edge.
You are given a 2d matrix which consist of the following symbols ".", "#", "|", where "." represent free cell, "#" represent a obstacle, "|" denotes shape. Your task is to find out the minimum obstacle to remove from the matrix so that the shapes falls down to the bottom.
Constraints
N/A
Example 1
Input:
matrix = [["*", "*", "*", "*"], ["#", "*", ".", "*"], [".", ".", "#", "."], [".", "#", ".", "#"]]
Output:
4
Explanation: Hence, return 4.
A sequence is considered harmonious if it can be divided into a series of groups, and each group starts with a number that indicates the number of items in that group, followed by exactly that many items.
For example, the sequence [3, 7, 2, 6, 2, 4, 4] is harmonious because it can be divided into two groups: [3, 7, 2, 6] and [2, 4, 4]. The first group begins with the number 3, indicating 3 elements following it. The second group begins with the number 2, indicating 2 elements following it.
Similarly, the sequence [1, 8, 4, 5, 2, 6, 1] is harmonious, as it can be divided into groups [1, 8] and [4, 5, 2, 6, 1] that satisfy the criteria.
However, the sequence [3, 2, 1] is not harmonious.
An empty sequence is harmonious.
You are given a sequence of integers A of length N.
In one operation, you can remove any element from the sequence. What is the minimum number of operations required to make the sequence harmonious?
Input
The input to the solution function consists of:
- A single integer
N(1 ≤ N ≤ 200,000) the length of the sequence A. - A sequence of N integers
A1, A2, A3...An(1 ≤ Ai ≤ 100,000) the elements of the sequence A. Output Return the answer, which is the minimum number of operations required to make the sequence harmonious.
Constraints
N/A
You are given a 0-indexed array nums of length n containing distinct positive integers. Return the minimum number of right shifts required to sort nums and -1 if this is not possible.
A right shift is defined as shifting the element at index i to index (i + 1 % n), for all indices.
Function Description
Complete the function minimumRightShiftsToSortArray in the editor.
minimumRightShiftsToSortArray has the following parameter:
int[] nums: a 0-indexed array containing distinct positive integers Returns int: the minimum number of right shifts required to sortnums, or-1if it is not possible
Constraints
1 ≤ nums.length ≤ 1001 ≤ nums[i] ≤ 100
Example 1
Input:
nums = [3,4,5,1,2]
Output:
2
Explanation: After the first right shift, nums = [2,3,4,5,1]. After the second right shift, nums = [1,2,3,4,5]. Now nums is sorted; therefore the answer is 2.
Example 2
Input:
nums = [1,3,5]
Output:
0
Explanation: nums is already sorted therefore, the answer is 0.
Example 3
Input:
nums = [2,1,4]
Output:
-1
Explanation: It's impossible to sort the array using right shifts.
Given a string, you can reverse part of it from any index towards left or right.
Output all possible list of strings.
Function Description
Complete the function reverseAndAppend in the editor.
reverseAndAppend has the following parameter:
String s: the original string ReturnsList: the list of all possible strings after reversing and appending Halooo~~ Uber assessment comes with 4 coding questions. The other 3 are in here - Generate Arrays (Click to view surprise :)
Example 1
Input:
s = "dbaacca"
Output:
["bdaacca", "abdacca", "dbaacac"]
Explanation: From index 1, reverse db-> append with rest of original -> bdaacca From index 2, reverse dba -> append with rest of original -> abdacca From index 5, reverse ca towards right -> append with rest of original -> dbaacac Output all possible list of strings PPS: I have a strong gut feeling that these might not be the correct versions of the output. The current outputs are just placeholders. I'll come back to update them once I find a more reliable source in the future. As for how far in the future… that's a myth no one knows. I'll see you next time!
You have a serial pipeline of services. Service i has base throughput throughputs[i] and scaling cost costs[i].
If you scale service i by a non-negative integer x, its throughput becomes throughputs[i] * (1 + x) and the scaling cost is x * costs[i].
Because the pipeline is serial, the overall throughput equals the minimum service throughput after scaling. Given a total budget, compute the maximum achievable overall throughput.
Function Description
Complete the function maximizePipelineThroughput in the editor below.
maximizePipelineThroughput has the following parameters:
int[] throughputs: base service throughputsint[] costs: scaling costs per extra multiplelong budget: the total scaling budget Returnslong: the maximum achievable pipeline throughput.
Example 1
Input:
throughputs = [5, 2, 4]
costs = [3, 10, 2]
budget = 0
Output:
2
Explanation:
With no budget, the pipeline throughput is the minimum base throughput, which is 2.
Example 2
Input:
throughputs = [5, 2, 4]
costs = [3, 10, 2]
budget = 20
Output:
4
Explanation:
Spending the full budget can raise the bottleneck service from 2 to 4, but not to 5.
You are given a 2D array. Your task is to find the regional maxima in the array and return a 2D array of size (X * 2) where each row contains the position [i, j] of a regional maximum.
Definition of Regional Maximum:
A cell (i, j) is considered a regional maximum if:
array[i][j] ≠ 0
array[i][j] is the maximum value within its region.
Definition of Region:
For a cell (i, j) with value cell:
The region is defined as the rectangular area (i - cell to i + cell) * (j - cell to j + cell).
Exclude the corner cells from above: (i - cell, j - cell), (i - cell, j + cell), (i + cell, j - cell) and (i + cell, j + cell).
If the calculated region goes out of bounds, ignore those out-of-bound cells.
Function Description
Complete the function findRegionalMaxima in the editor.
findRegionalMaxima has the following parameter:
int[][] array: a 2D array of integers Returnsint[][]: a 2D array where each row contains the position[i, j]of a regional maximum
Example 1
Input:
array = [[3, 0, 1], [2, 0, 0], [0, 0, 0]]
Output:
[[0, 0], [0, 2]]
Explanation:
The given 2D array is:
[
[3, 0, 1],
[2, 0, 0],
[0, 0, 0],
]
The cell at position [0, 0] with value 3 is a regional maximum because:
- It is not 0.
- Its region is from
[0, 0]to[3, 3](excluding corners and out-of-bounds), and it is the maximum in this region. The cell at position[0, 2]with value 1 is a regional maximum because: - It is not 0.
- Its region is from
[0, 1]to[1, 3](excluding corners and out-of-bounds), and it is the maximum in this region. Therefore, the output is[[0, 0], [0, 2]].
See the Image Source section at the very bottom of the page for the original problem statement Imagine you're given a string made entirely of digits, and your goal is to transform it by repeatedly applying a special operation whenever there are consecutive identical digits. Here's how it works: if a number has repeated digits, you replace each group of consecutive digits with their sum. For example, the number "999433" would become "2746" because 9 + 9 + 9 equals 27, and 3 + 3 equals 6. You keep doing this until there are no consecutive digits left. For instance, "44488366664" would first transform to "12163244." Keep applying this process until the string no longer has any repeating digits, and that's your final result. The challenge here is to find an approach that gets this done efficiently, though it doesn't need to be the most optimal one. Appreciation to Charlotte baby
Constraints
Example 1
Input:
number = "999433"
Output:
"2746"
Explanation: Because 9 + 9 + 9 = 27 and 3 + 3 = 6
Example 2
Input:
number = "44488366664"
Output:
"12163244"
Explanation: Following the same logic mentioned above, you will get --> 12163244
Example 3
Input:
number = "66644319333"
Output:
"26328"
Explanation: Imagine you’re given a number with consecutive digits that are the same, and your task is to transform it step by step. Let’s take the number "66644319333." First, you spot the consecutive equal digits: "666," "44," and "333." You replace each group with the sum of its digits: "666" becomes 18, "44" becomes 8, and "333" becomes 9. So, the number now transforms into "1883199." But wait, there are still consecutive equal digits, "88" and "99," so we apply the same process again. This time, "88" becomes 16, and "99" becomes 18, turning the number into "1163118." Once more, there are consecutive digits, "11" and another "11." Summing those gives us "26328," which is the final result, with no more repeats left. So, the final output is "26328."
Example 4
Input:
number = "0044886"
Output:
"084"
Explanation:
.
After one operation, number = "08166". Then it sequentially becomes 08112
P.S. The explanation isn't complete. I'll add more once I find more reliable source :)
See the Image Source section at the very bottom of the page for the original problem statement Civil engineers are using a digital elevation model to simulate how rainfall flows over terrain, represented as a 2D grid of integers where each number indicates the elevation at that point. The water starts flowing from a specific location, given by two coordinates (startRow, startCol), and moves to neighboring cells—up, down, left, or right—if the next cell's height is less than or equal to the current one. The water continues flowing until it can no longer move to any lower or equal elevation. Your task is to track this process by returning a new 2D grid, where each cell shows the time step when it first becomes wet, starting from 0 at the water's initial point. If a cell never gets wet, mark it as -1. The challenge is to design an efficient solution that works within a reasonable time limit, as water flow simulations can involve large terrain grids.
Example 1
Input:
heights = [[3, 2, 1], [6, 5, 4], [9, 8, 7]]
startRow = 1
startCol = 1
Output:
[[-1, 1, 2], [-1, 0, 1], [-1, -1, -1]]
Explanation: Unfortunately, we dont have the access to the video that explain why the expected output should be what it is rn. The terrain consists of a single cell. The starting point is this cell, so it becomes wet at time 0.
Example 2
Input:
heights = [[10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10]]
startRow = 1
startCol = 2
Output:
[[3, 2, 1, 2], [2, 1, 0, 1], [3, 2, 1, 2], [4, 3, 2, 3]]
Explanation: Water starts at cell (1, 2) and can flow to (imcomplete..will add once find more reliable source) Unfortunately, again, we dont have the access to the video explanation Water begins its journey at cell (1, 1) and spreads to neighboring cells with lower heights. The flow continues until there are no more adjacent cells that can be reached from the current wet cells. Each cell records the time step when it first becomes wet, with smaller numbers indicating earlier steps in the flow. The simulation halts when the water can no longer move. (This explanation might be incomplete, and I'll provide more details once I find a reliable source.)
There are some lamps placed on a coordinate line. Each of these lamps illuminates some space around it within a given radius. You are given the coordinates of the lamps on the line, and the effective radius of the lamps' light.
In other words, you are given a two-dimensional array lamps, where lamps[i] contains information about the i^th lamp. lamps[i][0] is an integer representing the lamp's coordinate, and lamps[i][1] is a positive integer representing the effective radius of the i^th lamp. That means that the i^th lamp illuminates everything in a range from lamps[i][0] - lamps[i][1] to lamps[i][0] + lamps[i][1] inclusive.
Your task is to find the coordinate of the point that is illuminated by the highest number of lamps. In case of a tie, return the point among them with the minimal possible coordinate.
Example 1
Input:
lamps = [[-2, 3], [2, 3], [2, 1]]
Output:
1
Explanation: The first lamp illuminates everything in range [-5, 1]. The second lamp illuminates everything in range [-1, 5]. The third lamp illuminates everything in range [1, 3]. The only point that is illuminated by all of the lamps is 1, hence the answer is 1.
Example 2
Input:
lamps = [[-2, 1], [2, 1]]
Output:
-3
Explanation: The given lamps illuminate ranges [-3, -1] and [1, 3] respectively. Every point in these ranges are illuminated by only 1 lamp, but the one with the minimal coordinate among them is -3, so it is the answer.
You have N ranges where the i-th range is from low[i] to high[i].
You need to create an array brr of length N. However, brr[i] can only be any prime number such that `low[i]
- It is guaranteed that there will be at least one element in
brr[i], which means there will always be a prime number betweenlow[i]andhigh[i]. - `low[i]
Constraints
1 ≤ N ≤ 10⁵1 ≤ low[i], high[i] ≤ 10⁶
Example 1
Input:
low = [1, 3]
high = [3, 5]
Output:
40
Explanation: We have 2 ranges, [1,3] and [3,5], there can be 4 ways of choosing 'brr', [(2,3),(3,5), (2,5),(3,3)] and scores of these will be [6,15,10,9], so sum of scores will be 40.
Example 2
Input:
low = [1, 2, 2]
high = [1, 2, 2]
Output:
8
Explanation: There is only a single way to choose 'brr' as [2,2,2] hence the answer will be 8.
Example 3
Input:
low = [1, 2, 3]
high = [4, 5, 30]
Output:
30
Explanation: There is only a single way to choose 'brr' as [2,3,5] hence the answer will be 30.
Given an integer array nums and an
Constraints
1 ≤ nums.length ≤ 2 * 10⁵-10⁹ ≤ nums[i] ≤ 10⁹1 ≤ k ≤ nums.length
Example 1
Input:
nums = [3, 2, 1, 5, 6, 4]
k = 2
Output:
[5, 6]
Explanation:
The two largest values are 5 and 6. Any order is acceptable.
You are given an array ranks representing players in tournament order. A smaller number means a stronger rank.
In each round, adjacent players compete: indices 0 and 1, indices 2 and 3, and so on. The player with the smaller rank number advances to the next round. If a round has an odd number of players, the last player advances automatically.
Return the list of rounds after each elimination round. Each inner array should contain the ranks that advanced from that round, in order. Continue until one player remains.
Function Description
Complete the function simulateTournamentRounds in the editor.
simulateTournamentRounds has the following parameter:
int ranks[]: player ranks in the initial bracket order Returnsint[][]: the advancing ranks after each round
Constraints
- Rank values are distinct.
- A smaller rank number represents a stronger player.
- If a round has an odd number of players, the last player advances automatically.
Example 1
Input:
ranks = [1, 2, 3, 4, 5, 6, 7, 8]
Output:
[[1, 3, 5, 7], [1, 5], [1]]
Explanation: In the first round, the winners are 1, 3, 5, and 7. Then 1 and 5 advance. Finally, 1 wins.
Example 2
Input:
ranks = [3, 1, 2]
Output:
[[1, 2], [1]]
Explanation: Player 1 beats player 3. Player 2 has no opponent in the first round and advances automatically.
Given a string, check if it is valid (return 1 :) or not (return 0 :). A valid string must: Be divisible by 3 (interpreted as the numeric value of the string is divisible by 3). Contain the digit '7' at least twice.
Example 1
Input:
s = "771"
Output:
1
Explanation: :)
Example 2
Input:
s = "777"
Output:
1
Explanation: :)
Example 3
Input:
s = "123777"
Output:
1
Explanation: :)
Example 4
Input:
s = "12345"
Output:
0
Explanation: :)
Example 5
Input:
s = "71"
Output:
0
Explanation: :)
Example 6
Input:
s = "171"
Output:
0
Explanation: :)
Example 7
Input:
s = "70"
Output:
0
Explanation: :)
Please check out the second source image below for more details :) Once upon a time in a land of letters and words, there was a curious puzzle that needed solving. The puzzle involved an array of words, each holding a special place in a magical list. The task was to find pairs of words that had a special relationship. Specifically, these pairs were defined by either the two words being exactly the same or one word starting with the other.
Constraints
N/A
Example 1
Input:
magics = ["back","backdoor", "gammon", "backgammon", "comeback", "come", "door"]
Output:
3
Explanation: The relevant pairs are: words[0] = "back" and words[1] = "backdoor" words[0] = "back" and words[3] = "backgommon" words[4] = "comeback" and words[5] = "come"
Example 2
Input:
magics = ["abc","a", "a", "b", "ab", "ac"]
Output:
8
Explanation: N/A for now
解锁全部 62 道题的解法
题面你已经看到了 — 解法 + 三语代码 + 复杂度推导 + 边界讨论, Pro 解锁.
- 📚1000+ 道真实北美 OA, Python / Java / C++ 三语题解
- 📊个人 dashboard + 进度可视化 + 14 天活跃图
- 📝题目笔记跨设备同步 + 个人复盘库
- 🔓随时取消下次续费, Stripe Customer Portal 自助管理