You are moderating a newspaper page, and you have to align the text on the page properly. The text is provided to you in the following format:
paragraphsis an array of paragraphs, where each paragraph is represented as an array of words.alignsis an array representing the alignment of each paragraph fromparagraphs— each element is either"LEFT"or"RIGHT".widthrepresents the maximum number of characters each line of the output can include.
For each paragraph, include all the words paragraphs[i][j], in order, separated by spaces:
- Include as many words as possible per page line (the length of the line must be less than or equal to
width), and put the next word on a new line if it would exceed this limit. - In the case of excess whitespace, words from
paragraphs[i]should be aligned according toaligns[i]. Ifaligns[i] = "LEFT", the line should have no leading spaces. - Include a border of
'*'characters around all the edges of the result.
解法
每个段落贪心装行:能装就继续,否则换行;按对齐填充后用 * 边框包裹。复杂度 O(total characters)。
def solution(paragraphs, aligns, width):
lines = []
for words, align in zip(paragraphs, aligns):
cur = []
cur_len = 0
for w in words:
extra = 1 if cur else 0
if cur_len + extra + len(w) <= width:
cur.append(w); cur_len += extra + len(w)
else:
lines.append((cur, align))
cur = [w]; cur_len = len(w)
if cur: lines.append((cur, align))
out = []
border = '*' * (width + 2)
out.append(border)
for words, align in lines:
line = ' '.join(words)
pad = width - len(line)
if align == "LEFT":
line = line + ' ' * pad
else:
line = ' ' * pad + line
out.append('*' + line + '*')
out.append(border)
return outclass Solution {
public List<String> newspaperLayout(String[][] paras, String[] aligns, int W) {
List<Object[]> lines = new ArrayList<>();
for (int p = 0; p < paras.length; p++) {
List<String> cur = new ArrayList<>(); int len = 0;
for (String w : paras[p]) {
int add = (cur.isEmpty() ? 0 : 1) + w.length();
if (len + add <= W) { cur.add(w); len += add; }
else { lines.add(new Object[]{cur, aligns[p]}); cur = new ArrayList<>(); cur.add(w); len = w.length(); }
}
if (!cur.isEmpty()) lines.add(new Object[]{cur, aligns[p]});
}
List<String> out = new ArrayList<>();
String border = "*".repeat(W + 2);
out.add(border);
for (Object[] ln : lines) {
String s = String.join(" ", (List<String>) ln[0]);
int pad = W - s.length();
s = ln[1].equals("LEFT") ? s + " ".repeat(pad) : " ".repeat(pad) + s;
out.add("*" + s + "*");
}
out.add(border);
return out;
}
}vector<string> newspaperLayout(vector<vector<string>>& paras, vector<string>& aligns, int W) {
vector<pair<vector<string>, string>> lines;
for (int p = 0; p < (int)paras.size(); ++p) {
vector<string> cur; int len = 0;
for (auto& w : paras[p]) {
int add = (cur.empty() ? 0 : 1) + (int)w.size();
if (len + add <= W) { cur.push_back(w); len += add; }
else { lines.push_back({cur, aligns[p]}); cur = {w}; len = w.size(); }
}
if (!cur.empty()) lines.push_back({cur, aligns[p]});
}
vector<string> out;
string border(W + 2, '*');
out.push_back(border);
for (auto& [ws, al] : lines) {
string s;
for (int i = 0; i < (int)ws.size(); ++i) { if (i) s += ' '; s += ws[i]; }
int pad = W - s.size();
s = (al == "LEFT") ? s + string(pad, ' ') : string(pad, ' ') + s;
out.push_back("*" + s + "*");
}
out.push_back(border);
return out;
}On the planet Octavia, astronomers track time using 8 distinct lunar phases instead of weekdays: NewMoon, Crescent, Quarter, Gibbous, Full, Waning, Eclipse, and Twilight. These phases repeat cyclically.
The Octavian year is divided into 12 seasons (January to December with Earth-month lengths), and each date has a corresponding lunar phase. Given a specific date (a season and day number) and the lunar phase with which the year began, determine the lunar phase for that date.
Notes:
- The number of days in each season in a non-leap year, in order: January: 31, February: 28, March: 31, April: 30, May: 31, June: 30, July: 31, August: 31, September: 30, October: 31, November: 30, December: 31.
- The lunar phases in the Octavian calendar are, in order:
NewMoon, Crescent, Quarter, Gibbous, Full, Waning, Eclipse, Twilight.
解法
自 1 月 1 日起的总天数 = season 前所有整月天数 + dayCount - 1。相位下标 = (start + total) mod 8。复杂度 O(1)。
def solution(season, dayCount, initialPhase):
phases = ["NewMoon", "Crescent", "Quarter", "Gibbous", "Full", "Waning", "Eclipse", "Twilight"]
days = {"January":31, "February":28, "March":31, "April":30, "May":31, "June":30,
"July":31, "August":31, "September":30, "October":31, "November":30, "December":31}
months_in_order = ["January","February","March","April","May","June","July","August","September","October","November","December"]
total = 0
for m in months_in_order:
if m == season: break
total += days[m]
total += dayCount - 1
start = phases.index(initialPhase)
return phases[(start + total) % 8]class Solution {
public String lunarPhase(String season, int dayCount, String initialPhase) {
String[] phases = {"NewMoon","Crescent","Quarter","Gibbous","Full","Waning","Eclipse","Twilight"};
String[] months = {"January","February","March","April","May","June","July","August","September","October","November","December"};
int[] days = {31,28,31,30,31,30,31,31,30,31,30,31};
int total = 0;
for (int i = 0; i < months.length; i++) { if (months[i].equals(season)) break; total += days[i]; }
total += dayCount - 1;
int start = 0; for (int i = 0; i < 8; i++) if (phases[i].equals(initialPhase)) { start = i; break; }
return phases[(start + total) % 8];
}
}string lunarPhase(string season, int dayCount, string initialPhase) {
vector<string> phases = {"NewMoon","Crescent","Quarter","Gibbous","Full","Waning","Eclipse","Twilight"};
vector<pair<string,int>> months = {{"January",31},{"February",28},{"March",31},{"April",30},{"May",31},{"June",30},
{"July",31},{"August",31},{"September",30},{"October",31},{"November",30},{"December",31}};
int total = 0;
for (auto& [m, d] : months) { if (m == season) break; total += d; }
total += dayCount - 1;
int start = find(phases.begin(), phases.end(), initialPhase) - phases.begin();
return phases[(start + total) % 8];
}Apply a sequence of commands to a matrix: swapRows r1 r2, swapColumns c1 c2, reverseRow r, reverseColumn c, rotate90Clockwise. Return the resulting matrix.
解法
直接模拟:除旋转外每个操作 O(R + C),旋转 O(R · C)。最坏总复杂度 O(K · R · C)。旋转通过转置后反转每行实现。
def robot_matrix(mat, cmds):
M = [row[:] for row in mat]
for cmd in cmds:
parts = cmd.split()
op = parts[0]
if op == 'swapRows':
r1, r2 = int(parts[1]), int(parts[2]); M[r1], M[r2] = M[r2], M[r1]
elif op == 'swapColumns':
c1, c2 = int(parts[1]), int(parts[2])
for row in M: row[c1], row[c2] = row[c2], row[c1]
elif op == 'reverseRow':
r = int(parts[1]); M[r].reverse()
elif op == 'reverseColumn':
c = int(parts[1])
col = [M[i][c] for i in range(len(M))][::-1]
for i in range(len(M)): M[i][c] = col[i]
else:
nr, nc = len(M), len(M[0])
M = [[M[nr - 1 - i][j] for i in range(nr)] for j in range(nc)]
return Mclass Solution {
public int[][] robotMatrix(int[][] mat, String[] cmds) {
int[][] M = mat;
for (String cmd : cmds) {
String[] parts = cmd.split(" ");
switch (parts[0]) {
case "swapRows": { int r1 = Integer.parseInt(parts[1]), r2 = Integer.parseInt(parts[2]); int[] t = M[r1]; M[r1] = M[r2]; M[r2] = t; break; }
case "swapColumns": { int c1 = Integer.parseInt(parts[1]), c2 = Integer.parseInt(parts[2]); for (int[] row : M) { int t = row[c1]; row[c1] = row[c2]; row[c2] = t; } break; }
case "reverseRow": { int r = Integer.parseInt(parts[1]); for (int i = 0, j = M[r].length - 1; i < j; i++, j--) { int t = M[r][i]; M[r][i] = M[r][j]; M[r][j] = t; } break; }
case "reverseColumn": { int c = Integer.parseInt(parts[1]); for (int i = 0, j = M.length - 1; i < j; i++, j--) { int t = M[i][c]; M[i][c] = M[j][c]; M[j][c] = t; } break; }
case "rotate90Clockwise": {
int nr = M.length, nc = M[0].length;
int[][] nw = new int[nc][nr];
for (int j = 0; j < nc; j++) for (int i = 0; i < nr; i++) nw[j][i] = M[nr - 1 - i][j];
M = nw; break;
}
}
}
return M;
}
}vector<vector<int>> robotMatrix(vector<vector<int>>& mat, vector<string>& cmds) {
auto M = mat;
for (auto& cmd : cmds) {
stringstream ss(cmd); string op; ss >> op;
if (op == "swapRows") { int r1, r2; ss >> r1 >> r2; swap(M[r1], M[r2]); }
else if (op == "swapColumns") { int c1, c2; ss >> c1 >> c2; for (auto& row : M) swap(row[c1], row[c2]); }
else if (op == "reverseRow") { int r; ss >> r; reverse(M[r].begin(), M[r].end()); }
else if (op == "reverseColumn") { int c; ss >> c; int n = M.size(); for (int i = 0; i < n / 2; ++i) swap(M[i][c], M[n-1-i][c]); }
else {
int nr = M.size(), nc = M[0].size();
vector<vector<int>> nw(nc, vector<int>(nr));
for (int j = 0; j < nc; ++j) for (int i = 0; i < nr; ++i) nw[j][i] = M[nr-1-i][j];
M = nw;
}
}
return M;
}A traveler visited a series of unique landmarks on a journey. Unfortunately, their travel journal was damaged, and they can no longer remember the exact order of their visits. However, they do have a collection of photos, each showing exactly two landmarks that were visited consecutively (either landmark could have been visited first).
Given the collection of photos represented as pairs of landmark IDs in travelPhotos, help the traveler reconstruct the complete journey. Each landmark was visited exactly once, and for every consecutive pair of landmarks in the journey, there exists a photo containing both landmarks.
You may reconstruct the journey in either forward or reverse order — both are considered correct.
Example: travelPhotos=[[3,5],[1,4],[2,4],[1,5]] → [3, 5, 1, 4, 2].
You are given an array of integers memory consisting of 0s and 1s which indicates whether the corresponding memory unit is free or not. memory[i] = 0 means that the iᵗʰ memory unit is free, and memory[i] = 1 means it's occupied.
The memory is aligned with segments of 8 units so all occupied memory blocks must start at an index divisible by 8 (e.g. 0, 8, 16, etc).
Your task is to perform two types of queries:
alloc x: Find the left-most aligned memory block ofxconsecutive free memory units and mark these units as occupied (i.e., find the left-most contiguous subarray of 0s, starting at positionstartwhich is divisible by 8, and replace all these memory units with 1s). If there is no proper aligned memory block withxconsecutive free units, return-1; otherwise return the index of the first position of the allocated block segment and assign anIDto every single element in the block, based on an atomic counter (the counter starts at 1 and is incremented on every successful alloc operation). Note:xmay be greater than 8, so the block may cover more than one memory segment.erase ID: Find if a block exists with thisID. If so, free the memory units with thisID(set them to 0) and return the number of memory units freed; otherwise return-1.
The queries are given in the form of 2-element arrays:
- If
queries[i][0] = 0—alloctype query, wherex = queries[i][1]. - If
queries[i][0] = 1—erasetype query, whereID = queries[i][1].
You are developing a new programming language. You believe that ordinary dictionaries are boring, so you've decided to add a cool feature to make your language unique! You want the cool feature to be able to perform two types of queries. With two integer arrays, a and b, the two types of queries are as follows:
- If the query is of the form
[0, i, x], then addxtoa[i](a[i]should be assigned the value ofa[i] + x). - If the query is of the form
[1, x], then find the total number of pairs of indicesiandjsuch thata[i] + b[j] = x.
You will be given the arrays of integers a and b, as well as queries, an array of queries in either of the forms described above. Your task is to implement this cool feature, perform the given queries and return an array of the results of the queries of the type [1, x].
You are tasked with analyzing the potential space in a cityscape outlined by a series of skyscrapers. Each skyscraper's height is represented by an element in the array cityLine, where the width of each skyscraper is consistently 1, and they are placed directly adjacent to each other along a road with no gaps. Your mission is to determine the largest square area that can fit inside the row of skyscrapers.
Example: cityLine=[1, 2, 3, 2, 1] → 4. cityLine=[4, 3, 4] → 9.
You are given a list of file segments, each described by (start, length) and a stream of bytes arriving one-by-one. After each new byte, return the number of segments that are now fully covered (every offset in [start, start + length) has been seen).
Imagine you are reorganizing a library database that uses a unique system to catalog books. Each book is identified by a name stored in a list, titles. Your task is to find how often a book name serves as a beginning segment of another book name or if the book itself starts another book name. Essentially, determine how many pairs i ≠ j (0 ≤ i ≠ j < titles.length) exist such that titles[i] is a prefix of titles[j]. Returns the count output of pairs.
Example: titles=["wall","wallpaper","science","wallet","philosophy","phil"] → 3.
You've decided to create a bot for handling stock trades. For now, you have a simple prototype which handles trades for just one stock. Each day, it's programmed to either buy or sell one share of the stock. You are given prices, an array of positive integers where prices[i] represents the stock price on the iᵗʰ day. You're also given algo, an array of zeros and ones representing the bot's schedule, where 0 means buy and 1 means sell.
In order to improve the bot's performance, you'd like to choose a range of k consecutive days where the bot will be programmed to sell. In other words, set a range of k consecutive elements from algo to 1. Your task is to choose the interval such that it maximizes the bot's total revenue (= sum of all selling prices minus sum of all buying prices). The difference between the end and start amount.
NOTE: Assume you begin with enough shares of the stock that it's always possible to sell.
Example: prices=[2,4,1,5,2,6,7], algo=[0,1,0,0,1,0,0], k=4 → 21.
Imagine that you're exploring a mysterious labyrinth in the shape of a rectangular matrix, which contains obstacles and teleports. Starting from the upper-left corner, your goal is to reach the lower-right corner by first moving to the right, and then moving down if that doesn't work.
You are given integers n and m representing the dimensions of the labyrinth. You are also given obstacles and teleports, which are lists of the cells that contain all the obstacles and teleports, respectively.
Rules:
- An obstacle cannot be traversed — if there's an obstacle in the cell to your right, try moving down. If there are obstacles in the cells to the right and below, stop immediately.
- A teleport is a pair of cells
(start, end). If you reach thestartcell, you immediately move to theendcell. (Doesn't work backwards.) - All teleport
startcells are unique. - A teleport's
endcell cannot be astartfor another teleport. - Both
startandendof teleports are non-obstacle.
Return the total count of cells traveled through to reach the exit, including start (0, 0), both start and end cells of teleports. Return -1 for obstacle blockage, -2 for infinite teleport loop.
Given two arrays of ingredients and recipes, for each recipe in recipes, find out whether it is a prep-list combination of ingredients. As a result, return an array of booleans where recipes[i] is a prep-list combination of ingredients, and false otherwise.
A string recipe is a prep-list combination of an array ingredients if there is a way to split recipe into k (k ≥ 1) consecutive non-empty parts such that the iᵗʰ part is in ingredients.
Example: ingredients=["flour", "sugar", "eggs"], recipes=["floursugar","random","flour","sugarflour","sugareggs"] → [true, false, true, false, true].
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 integer array nums (each number may have multiple digits and can include 0), return the count of elements whose number of digits in base-10 is even.
The number of digits of x is the length of its decimal representation. For example, 7 has 1 digit, 12 has 2 digits, and 0 has 1 digit.
Input
An integer array nums
Output
An integer: the count of numbers with an even number of digits Constraints (typical) 1 ≤ len(nums) ≤ 1e5 0 ≤ nums[i] ≤ 1e9
Examples
Input: [12, 345, 2, 6, 7896] → Output: 2 Input: [555, 901, 482, 1771] → Output: 1 Input: [0, 10, 100, 1000] → Output: 2 Input: [8] → Output: 0 Input: [22, 33, 4444, 5, 666666] → Output: 3
Function Description
Complete solveOneCountEvenDigitNumbers. 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 = "12 345 2 6 7896"
Output:
["2"]
Explanation: The returned string must match the expected standard output for the sample input.
Complete the function below. The function receives the full standard input as a single string and must return the exact standard output value for the described problem.
Given an integer array nums of length n and an integer t (0 ≤ t < n). Define one cyclic shift as moving the last t elements of the array to the front (i.e., a right rotation by t).
Determine whether applying this shift once makes the array strictly descending.
Return true/false.
Note: The original description is slightly ambiguous about whether t is given or you may choose t. This version assumes t is given and you check the result after one shift.
Input
Integer array nums Integer t
Output
true or false. Constraints (suggested) 1 ≤ n ≤ 2·10⁵, 0 ≤ t < n, -10⁹ ≤ nums[i] ≤ 10⁹.
Examples
nums=[3,2,1], t=0 → true nums=[1,3,2], t=1 → false nums=[2,1,3], t=2 → false nums=[4,3,2,1], t=1 → false nums=[2,1], t=1 → false
Function Description
Complete solveOneCyclicShiftStrictlyDescending. It has one parameter, String input, containing the full stdin payload. Return the exact stdout value as a string, either "true" or "false".
Constraints
Use the limits and requirements stated in the prompt.
Example 1
Input:
input = "3\n3 2 1\n0"
Output:
"true"
Explanation: The returned string must match the expected standard output for the sample input.
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.
Maintain a 1D line of length n with indices 0..n-1, initially with no walls.
You are given a sequence of operations of two types:
build i: build a wall at index i (idempotent). query l r: check whether there exists at least one wall in the inclusive range [l, r].
For each query output:
1 if the range contains a wall otherwise 0
Return/output the list of query results in order.
Input
Integer n List of operations operations
Output
List of 0/1 (or printed space-separated) Constraints (suggested) 1 ≤ n ≤ 2e5 1 ≤ len(operations) ≤ 2e5 indices are valid
Examples
n=5, ops=[query 0 4] → 0 n=5, ops=[build 2, query 0 4] → 1 n=5, ops=[build 2, query 3 4] → 0 n=5, ops=[build 1, build 3, query 2 2, query 0 3] → 0 1 n=3, ops=[build 0, build 0, query 0 0, query 1 2] → 1 0
Function Description
Complete solveOneDynamicWallRangeQuery. 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 = "5\n1\nquery 0 4"
Output:
["0"]
Explanation: The returned string must match the expected standard output for the sample input.
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.
There is a single check-in line. You are given an integer array arrivalTimes where arrivalTimes[i] is the time when person i arrives at the end of the line.
Rules:
Only one person is processed at a time. The person at the front takes 30 seconds to check in. When a person arrives, if the number of people currently waiting/being served in the system is greater than 10, that person leaves immediately and will not check in.
Return an array result:
If person i is served, result[i] is the time they start service. Otherwise, result[i] = null.
Assume arrivalTimes is non-decreasing; ties are enqueued in input order.
Input
Integer array arrivalTimes
Output
Array result (each entry is an integer or null) Constraints (suggested) 1 ≤ len(arrivalTimes) ≤ 2e5 0 ≤ arrivalTimes[i] ≤ 1e9
Examples
arrival=[0,0,0] → result=[0,30,60] arrival=[0,10,20] → result=[0,30,60] arrival=[0,100] → result=[0,100] 12 people arrive at time 0 → first 11 served, 12th leaves arrival=[0,15,15,16] → result=[0,30,60,90]
Function Description
Complete solveOneQueueCheckInSimulation. 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.
When multiple tasks are included in a single thread/CPU, the tasks are scheduled based on the principle of preemption. When a higher priority task arrives, the currently executing task with lower priority gets preempted, i.e., it becomes idle until the higher priority task is complete.
There are 3 functions to be executed in a single thread with IDs between 0 and n-1. Given an integer n representing the number of functions to be executed, and an array logs containing the timestamp and function ID, determine the exclusive time of each of the functions. It is noted that the total of execution time should be divided among functions according to their representing an integer log in the form {function_id, "start"|"end", timestamp} indicating when a function started or ended at a time identified by the timestamp value.
Note: While calculating the execution time of a function both the starting and ending times of the function calls are to be included. The log of the function calls is sorted by timestamp. When a function is preempted at the beginning of timestamp second, the log of this time stamp is {"preempting_id", "start", timestamp}. When a function function_id is preempted after completing timestamp second, the log record is {"after_timestamp_record"}.
Function Description
Complete the function getFunctionExecutionTime in the editor.
getFunctionExecutionTime has the following parameters:
-
int n: the number of functions to be executed
-
String logs[m]: the execution logs of the different calls to the functions Returnsint[n]: the execution time of all functions with IDs [0,n-1] , Aura Man with the hard carry!༊·°𓍼ོ
Constraints
- 1 ≤ n ≤ 100
- 1 ≤ m ≤ 500
- 0 ≤ function_id
Example 1
Input:
n = 3
logs = ["0:start:0", "2:start:4", "2:end:5", "1:start:7", "1:end:10", "0:end:11"]
Output:
[6, 4, 2]
Explanation: Suppose n = 3, logs = ["0:start:0", "2:start:4", "2:end:5", "1:start:7", "1:end:10", "0:end:11"] Thus the total number of seconds allocated to functions 0, 1, and 2 is 6, 4, and 2 respectively. Hence the answer is [6, 4, 2].
tomtom's note: Feel free to check out the source image below for the original problem statement :) Imagine you have a beautiful square matrix and a number, turns. Your mission is to gracefully rotate this matrix turns times "over its diagonals," creating a new, enchanting pattern with each rotation. After you've completed the rotations, you'll return the transformed matrix, now dressed in its new, elegant arrangement. The elements along the two main diagonals remain beautifully in place, untouched by the rotation. However, the four sections formed by these diagonals gracefully swap positions in a clockwise dance. With each rotation, these segments move to their new spots, creating a fresh, charming pattern. Take a look at the images below to see this elegant transformation in action!
Example 1
Input:
matrix = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20],[21, 22, 23, 24, 25]]
turns = 1
Output:
[[1, 16, 11, 6, 5], [22, 7, 12, 9, 2], [23, 18, 13, 8, 3], [24, 17, 14, 19, 4], [21, 20, 15, 10, 25]]
Explanation:
Given a list, for each element in the list, repeatedly sum the digits until it becomes a single-digit number. Then return the mode of the resulting numbers.
For example:
['1234', '24', '33'] → ['10', '6', '6'] → ['1', '6', '6']
So the result is 6.
Function Description
Complete the function sumDigitsUntilOne in the editor.
sumDigitsUntilOne has the following parameter:
List numbers: a list of strings representing numbers Returnsint: the mode of the single-digit numbers obtained by repeatedly summing the digits
Example 1
Input:
numbers = ["1234", "24", "33"]
Output:
6
Explanation: The process of summing the digits repeatedly until a single-digit number is obtained is as follows:
- 1234 → 1+2+3+4 = 10 → 1+0 = 1
- 24 → 2+4 = 6
- 33 → 3+3 = 6 The resulting single-digit numbers are 1, 6, and 6. The mode of these numbers is 6.
解锁全部 16 道题的解法
题面你已经看到了 — 解法 + 三语代码 + 复杂度推导 + 边界讨论, Pro 解锁.
- 📚1000+ 道真实北美 OA, Python / Java / C++ 三语题解
- 📊个人 dashboard + 进度可视化 + 14 天活跃图
- 📝题目笔记跨设备同步 + 个人复盘库
- 🔓随时取消下次续费, Stripe Customer Portal 自助管理