You are given an array of integers numbers. Your task is to count the number of distinct pairs of indices (i, j) (where i < j) such that numbers[i] can be obtained from numbers[j] by swapping exactly two digits in their decimal representation. Both numbers must have the same number of digits to be considered.
Example: numbers = [1, 23, 156, 1650, 651, 165, 32] returns 3 (pairs: (23, 32), (156, 651), (156, 165)).
Constraints
1 ≤ numbers.length ≤ 10⁴, 1 ≤ numbers[i] ≤ 10⁹.
解法
按 (位数, 排序后字符多重集) 分桶;同桶里两两比较字符串,若恰好两位不同则计数。不同桶之间不可能通过单次交换得到,所以可以剪枝。复杂度 O(n·L + Σ m²·L),L 为数字位数。
def solution(numbers):
buckets = {}
for v in numbers:
s = str(v); key = (len(s), ''.join(sorted(s)))
buckets.setdefault(key, []).append(s)
ans = 0
for arr in buckets.values():
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
if sum(1 for a, b in zip(arr[i], arr[j]) if a != b) == 2:
ans += 1
return ansclass Solution {
public int solution(int[] numbers) {
Map<String, List<String>> buckets = new HashMap<>();
for (int v : numbers) {
String s = String.valueOf(v);
char[] arr = s.toCharArray();
Arrays.sort(arr);
String key = s.length() + ":" + new String(arr);
buckets.computeIfAbsent(key, k -> new ArrayList<>()).add(s);
}
int ans = 0;
for (List<String> arr : buckets.values()) {
int m = arr.size();
for (int i = 0; i < m; i++) for (int j = i + 1; j < m; j++) {
int diff = 0;
String a = arr.get(i), b = arr.get(j);
for (int p = 0; p < a.length(); p++) if (a.charAt(p) != b.charAt(p)) diff++;
if (diff == 2) ans++;
}
}
return ans;
}
}int solution(vector<int>& numbers) {
map<pair<int, string>, vector<string>> buckets;
for (int v : numbers) {
string s = to_string(v), sorted_s = s;
sort(sorted_s.begin(), sorted_s.end());
buckets[{(int)s.size(), sorted_s}].push_back(s);
}
int ans = 0;
for (auto& [_, arr] : buckets) {
int m = arr.size();
for (int i = 0; i < m; ++i) for (int j = i + 1; j < m; ++j) {
int diff = 0;
for (int p = 0; p < (int)arr[i].size(); ++p)
if (arr[i][p] != arr[j][p]) ++diff;
if (diff == 2) ++ans;
}
}
return ans;
}You're given a square matrix matrix of size n × n. Define a bouncing diagonal starting from the left column as the sequence of elements obtained by starting at some cell (i, 0), moving diagonally up-right until hitting the top row, then bouncing diagonally down-right, and so on (alternating direction whenever you hit top or bottom).
Define the weight of a leftmost-column element as the sum of all elements in its bouncing diagonal. Return the leftmost column reordered so that weights are in ascending order. In case of a tie, sort by value in ascending order.
Example: for matrix = [[1,2,3],[4,5,6],[7,8,9]], row 0's diagonal is 1+5+9=15 (down-right), row 1's bounces 4+8+6=18, row 2's bounces 7+5+3=15. Weights (15,15,18) after tie-break by value give new first column [1, 7, 4].
解法
枚举每个起始行模拟反弹路径,逐格累加得到权重;把首列元素按 (权重, 值) 排序后写回首列。模拟一条路径走 n 步,共 n 行,复杂度 O(n²)。
def solution(matrix):
n = len(matrix)
weights = []
for start in range(n):
r, c, dr, s = start, 0, -1, 0
while c < n:
s += matrix[r][c]
if r == 0: dr = 1
elif r == n - 1: dr = -1
r += dr; c += 1
if r < 0 or r >= n: r = max(0, min(n - 1, r))
weights.append((s, start))
weights.sort()
col = [matrix[orig][0] for _, orig in weights]
for i in range(n): matrix[i][0] = col[i]
return matrixclass Solution {
public int[][] solution(int[][] matrix) {
int n = matrix.length;
long[][] weights = new long[n][2];
for (int start = 0; start < n; start++) {
int r = start, c = 0, dr = -1;
long s = 0;
while (c < n) {
s += matrix[r][c];
if (r == 0) dr = 1;
else if (r == n - 1) dr = -1;
r += dr; c++;
if (r < 0 || r >= n) r = Math.max(0, Math.min(n - 1, r));
}
weights[start][0] = s; weights[start][1] = start;
}
Arrays.sort(weights, (a, b) -> a[0] != b[0] ? Long.compare(a[0], b[0]) : Long.compare(a[1], b[1]));
int[] col = new int[n];
for (int i = 0; i < n; i++) col[i] = matrix[(int) weights[i][1]][0];
for (int i = 0; i < n; i++) matrix[i][0] = col[i];
return matrix;
}
}vector<vector<int>> solution(vector<vector<int>> matrix) {
int n = matrix.size();
vector<pair<long long, int>> weights;
for (int start = 0; start < n; ++start) {
int r = start, c = 0, dr = -1;
long long s = 0;
while (c < n) {
s += matrix[r][c];
if (r == 0) dr = 1;
else if (r == n - 1) dr = -1;
r += dr; c += 1;
if (r < 0 || r >= n) r = max(0, min(n - 1, r));
}
weights.push_back({s, start});
}
sort(weights.begin(), weights.end());
vector<int> col(n);
for (int i = 0; i < n; ++i) col[i] = matrix[weights[i].second][0];
for (int i = 0; i < n; ++i) matrix[i][0] = col[i];
return matrix;
}You are given a string binaryString consisting of '0's and '1's, and an array of strings requests containing requests of two types:
requests[i] = "count:<index>"— find the number of'0's inbinaryStringbefore and including the specified 0-basedindex.requests[i] = "flip"— flip all elements ofbinaryString(every'0'becomes'1'and every'1'becomes'0').
Return an array answers, where answers[i] contains the answer for the respective count request.
Example: binaryString="1111010", requests=["count:4","count:6","flip","count:4","flip","count:2"] → [1, 2, 4, 0].
解法
预计算原串 '0' 的前缀和 z[];flip 不真翻,只切换布尔 flipped。每次 count(idx) 时若被翻转,输出 (idx+1) - z[idx](原串 '1' 的数量即翻转后的 '0'),否则直接返回 z[idx]。每查询 O(1)。
def solution(s, requests):
n = len(s); pz = [0] * (n + 1)
for i, c in enumerate(s): pz[i + 1] = pz[i] + (c == '0')
flipped = False; out = []
for r in requests:
if r == "flip": flipped = not flipped
else:
idx = int(r.split(":")[1]); z = pz[idx + 1]
out.append((idx + 1) - z if flipped else z)
return outclass Solution {
public List<Integer> solution(String s, String[] requests) {
int n = s.length();
int[] pz = new int[n + 1];
for (int i = 0; i < n; i++) pz[i + 1] = pz[i] + (s.charAt(i) == '0' ? 1 : 0);
boolean flipped = false;
List<Integer> out = new ArrayList<>();
for (String r : requests) {
if (r.equals("flip")) flipped = !flipped;
else {
int idx = Integer.parseInt(r.substring(6));
int z = pz[idx + 1];
out.add(flipped ? (idx + 1) - z : z);
}
}
return out;
}
}vector<int> solution(string s, vector<string>& requests) {
int n = s.size();
vector<int> pz(n + 1, 0);
for (int i = 0; i < n; ++i) pz[i + 1] = pz[i] + (s[i] == '0' ? 1 : 0);
bool flipped = false;
vector<int> out;
for (auto& r : requests) {
if (r == "flip") flipped = !flipped;
else {
int idx = stoi(r.substr(6));
int z = pz[idx + 1];
out.push_back(flipped ? (idx + 1) - z : z);
}
}
return out;
}Given an empty array that should contain integer numbers, your task is to process a list of queries on it. Specifically, there are two types of queries:
"+x"— appendxto numbers. numbers may contain multiple instances of the same number."-x"— remove all the instances ofxfrom numbers.
After processing each query, count the number of triples (x, y, z) in numbers which meet this condition: both x - y and y - z are equal to a given diff. The final output should be an array of counts after each query.
Example: queries=["+4","+5","+6","+4","+3","-4"], diff=1 returns [0, 0, 1, 2, 4, 0].
Constraints
values in [-10⁹, 10⁹]; at most 10⁵ queries.
You are given operations, an array containing the following two types of operations:
(0, a, b)— Create and save a rectangle of sizea × b.(1, a, b)— Answer the question: "Could every one of the earlier saved rectangles fit in a box of sizea × b?". It is possible to rotate rectangles by 90 degrees; i.e., a rectangle of dimensionsa × bcan be rotated so that its dimensions areb × a. Note: We're trying to fit each rectangle within the box separately (not all at the same time).
Your task is to return an array of booleans, representing the answers to the second type of operation, in the order they appear.
Example: operations = [[0,1,3],[0,4,2],[1,3,4],[1,3,2]] returns [true, false]. After saving 1×3 and 4×2, a 3×4 box fits both (rotate 4×2 to 2×4); a 3×2 box can't fit 4×2.
Given an infinite integer number line, you would like to build some blocks and obstacles on it. Specifically, you have to implement code which supports two types of operations:
[1, x]— builds an obstacle at coordinatexalong the number line. Guaranteed that coordinatexdoesn't contain obstacles when called.[2, x, size]— checks whether it's possible to build a block of sizesizewhich ends immediately beforexon the number line. For example,x=6, size=2checks coordinates 4 and 5. Produces"1"if possible,"0"otherwise.
Return a binary string of outputs for all [2, x, size] operations.
Example: operations = [[1,2],[1,5],[2,5,2],[2,6,3],[2,2,1],[2,3,2]] returns "1010". Obstacles at 2 and 5; queries check [3,4], [3,5], [1,1], [1,2] respectively.
Constraints
1 ≤ operations.length ≤ 10⁵, coordinates in [-10⁹, 10⁹].
Given a square matrix n × n (n guaranteed odd) containing only 0s, 1s, or 2s. In one operation, you change any cell to a different digit (0, 1, or 2). Find the minimum number of cells to change so that letter "Y" is written on the matrix.
The letter "Y" is written on the matrix if and only if:
- all numbers on the diagonals from upper-left and upper-right corners down to the center, as well as numbers stretching down vertically from the center to the bottom, are equal;
- all other numbers (not part of "Y") should be equal to and different from the "Y" digit.
Example: n = 3, matrix = [[1,0,1],[2,1,2],[2,1,2]]. Picking Y digit = 1 and background = 2 costs 1 change (cell (1,0) from 2 to 2 is free, count the actual mismatch). Try all 6 (Y digit, background) ordered pairs and take the minimum.
Constraints
1 ≤ n ≤ 99, n is odd.
All the competitors in a stock car race have completed their qualifying laps. Each lap, the driver with the current slowest "best" time is eliminated (that is, the highest personal best time). If multiple drivers tie for the slowest time, they are all eliminated.
You are given a two-dimensional string array with each driver's name and lap time in seconds for each lap. Your task is to return the drivers in the order in which they were eliminated, ending with the last driver or drivers remaining. When multiple drivers are eliminated on the same lap, their names should be listed alphabetically.
Example: laps = [["Harold 154","Gina 155","Juan 160"],["Juan 152","Gina 153","Harold 148"],["Harold 148","Gina 150","Juan 149"]] returns ["Juan","Harold","Gina"].
You are given an array of non-negative integers. Repeatedly perform the following procedure until every element is zero:
- Find the index of the leftmost non-zero element. Let its value be
x. - Starting at that index and going to the right, subtract
xfrom every element whose value is at leastx. - Add
xto the running result.
Return the resulting sum. It is guaranteed that the algorithm terminates.
Example: arr = [0, 2, 2, 0, 3]. Round 1: x = 2, array becomes [0, 0, 0, 0, 1], result = 2. Round 2: x = 1, array becomes [0, 0, 0, 0, 0], result = 3. Return 3.
Constraints
1 ≤ arr.length ≤ 10⁴, 0 ≤ arr[i] ≤ 10⁴.
Given an integer n, return a list of n strings. Each string consists of n asterisks separated by single spaces.
Example: n = 2 returns ["* *", "* *"]. n = 5 returns five copies of "* * * * *". n = 8 returns eight copies of "* * * * * * * *".
Constraints
1 ≤ n ≤ 100.
tomtom's note: Feel free to check out source image for the original problem statement :) Imagine a vast grid-like board, stretching across numRows by numColumns, where a little robot begins its journey. This robot, however, isn’t alone on the board—there are dangerous lasers positioned at specific coordinates, marked by the array laserCoordinates. Each laser is like a sentinel, protecting its row and column by destroying anything that dares to cross its path. Our brave robot starts its adventure at a particular spot on the board, given by the coordinates (curRow, curColumn). It’s protected from the laser beams in its starting position, but the moment it moves, it’s in danger. The robot can only move in straight lines—either left, right, up, or down—but it must be cautious. The robot’s goal is to explore the board and count the maximum number of cells it can safely move through before any of the laser beams find and destroy it.
Example 1
Input:
numRows = 8
numColumns = 8
curRow = 5
curColumn = 3
laserCoordinates = [[1, 6], [2, 8]]
Output:
3
Explanation: Picture an 8x8 board where a courageous little robot is about to embark on a perilous journey. But danger lurks in the form of two powerful lasers, positioned at the coordinates (1, 6) and (2, 8). These lasers are like sentinels, guarding their rows and columns fiercely, ready to destroy anything that crosses their path.
Plz check out the source image below for the origina
Example 1
Input:
queries = ["+4", "+5", "+6", "+4", "+3", "-4"]
diff = 1
Output:
[0, 0, 1, 2, 4, 0]
Explanation: Plz check out srcImages below for the explanation
tomtom's note: Feel free to check out the source image below for the original problem statement :) Imagine you're given a string of digits called panel and an array of strings called codes. Each string in the codes array is made up of digits and follows a specific format: " ", where both the index and pattern are composed of at least one digit. Since there are several possible ways to split the code into the index and pattern, we'll explore all of them, starting with the smallest index length. For example, if the code is "1324", the possible splits would be: split-case 1: index = "1" and pattern = "324" split-case 2: index = "13" and pattern = "24" split-case 3: index = "132" and pattern = "4" For each code in the codes array, and for every split-case of this code, we'll check whether the pattern appears at the specified index in the panel string. You'll receive a string array as a result, where each element will either be the pattern (if it’s found in the panel at the correct position) or "not found" if it isn’t. Don’t worry about making your solution the fastest possible, but it should work efficiently enough given the size of the inputs.
Constraints
1 ≤ panel.length ≤ 10³
Example 1
Input:
board = "2311453915"
keys = ["0211", "639"]
Output:
["not found", "11", "not found", "39", "not found"]
Explanation: Once upon a time, in the land of digits, there was a string called panel and a group of secret codes known as codes. Each code was a puzzle, with two parts hidden within: an index and a pattern. The task was to discover if the pattern appeared in the panel at the exact spot indicated by the index. To uncover this, we had to explore all possible ways to split each code, like peeling back layers of a mystery. Let’s begin with the first code, "0211." There were three different ways to split it: In the first split-case, we tried index "0" and pattern "211." We searched for "211" starting from the 0th position in the panel, but the panel revealed "231," not our pattern. Sadly, this wasn’t the correct code. The answer: "not found." Next, we tried index "02" and pattern "11." To our delight, the panel whispered back "11" at the right spot. This was the correct code! The answer: "11." Lastly, we explored index "021" with pattern "1." But the panel had nothing to offer at such a distant place—it was simply too far. The answer: "not found." Then came the second code, "639," with two possibilities: First, we tried index "6" and pattern "39." The panel responded perfectly, showing "39" right where we hoped. The code was valid! The answer: "39." Finally, we tried index "63" with pattern "9," but the panel’s digits didn’t stretch that far. Once again, the answer was "not found." And so, the results of this little adventure were a collection of answers: ["not found", "11", "not found", "39", "not found"], each reflecting the success or failure of our code-breaking journey.
To view the original problem statement, pls check out the source image below Imagine you have an empty collection of numbers, and you're given a list of instructions to add or remove numbers from this collection. Your task is to follow these instructions carefully and, after each one, count how many special groups of three numbers (we call them "triples") can be made from the numbers in your collection. Here's how a triple works: you need to pick three numbers, let’s call them x, y, and z. For them to count as a triple, the difference between x and y must be the same as the difference between y and z. This means that if you rearrange the numbers correctly, they should form a nice pattern like x, y, z. For each instruction, you either add a new number to your collection or remove all instances of a specific number from it. After every single instruction, you have to check how many triples you can make with the current set of numbers. The story has a few rules to keep things interesting: The numbers involved are very large and can range from extremely negative to extremely positive. When you're asked to remove a number, you can be sure that the number is actually in the collection—no need to worry about trying to remove something that isn’t there. Finally, no matter how many triples you end up counting, the result will always be small enough to fit in a standard counting device. Your ultimate goal is to create a list of these counts after processing each instruction, showing how the number of possible triples changes as you add or remove numbers.
tomtom's note: Feel free to check out the source image below for the original problem statement :) Once upon a time, there was a magical array of numbers, each with its own unique set of digits. These numbers had a secret ability: they could rearrange themselves by performing a special move called a "cyclic shift." This meant they could take some digits from the end and move them to the front, while shifting all the other digits over in the same order. If two numbers could be transformed into each other through this shifting magic, they were known as "cyclic pairs."
note - see the Problem Source below for the original problem description ;) Imagine you’re given a list of numbers, and your task is to calculate the difference between two specific sums. First, you’ll sum up all the numbers at even positions (remember, the list is 0-based) that fall between -100 and 100, inclusive. Then, you’ll do the same for numbers at odd positions that also lie within this range. Finally, you’ll subtract the odd-positioned sum from the even-positioned sum to get your answer. Just make sure your solution is efficient, ideally not taking more than O(n) time, though a slightly slower approach will also work fine.
Constraints
1 ≤ numbers.length ≤ 10³-10³ ≤ numbers[i] ≤ 10³
Example 1
Input:
numbers = [101, 3, 4, 359, 2, 5]
Output:
-2
Explanation: Let’s break it down: you want to find the sums of certain elements from your list based on their positions and values. For the even-positioned elements, you only consider those at positions 2 and 4 because their values are within the range of [-100, 100]. In this case, numbers[2] is 4 and numbers[4] is 2, giving you a total of 6. numbers[0] = 101 is excluded because it’s outside the range. Next, for the odd-positioned elements, you check numbers[1] and numbers[5], which are 3 and 5, respectively, totaling 8. Here, numbers[3] = 359 is filtered out because it doesn’t meet the criteria. Finally, you subtract the sum of the odd-positioned elements (8) from the sum of the even-positioned elements (6), resulting in 6 - 8 = -2. Thus, the expected output is -2.
Example 2
Input:
numbers = [-2, 234, 100, 99, 540, -1]
Output:
0
Explanation: For the even-positioned elements, you check the values at positions 0 and 2. Here, numbers[0] = -2 and numbers[2] = 100, which adds up to 98. numbers[4] = 540 is excluded since it exceeds the range of [-100, 100]. Next, for the odd-positioned elements, you look at numbers[1] and numbers[5]. In this case, numbers[3] = 99 and numbers[5] = -1, giving a total of 98 as well. numbers[1] = 234 is filtered out because it is outside the specified range. Finally, you subtract the sum of the odd-positioned elements (98) from the sum of the even-positioned elements (98), resulting in 98 - 98 = 0. Therefore, the expected output is 0.
Example 3
Input:
numbers = [-9]
Output:
-9
Explanation: In your list, the only even-positioned element is at position 0, which is -9. This value is within the range of [-100, 100], so it contributes to the sum, making the total for even positions -9. For the odd-positioned elements, there are none present, resulting in a sum of 0. Now, when you subtract the sum of the odd-positioned elements (0) from the sum of the even-positioned elements (-9), you get -9 - 0 = -9. Thus, the expected output is -9.
A grid contains a start cell S, a destination cell D, and cells labeled 1, 2, 3, or 4 for four commute modes. A commute mode may move through S, D, and cells labeled with that mode's digit only.
For each mode, find the shortest number of steps from S to D. The total time is steps * times[mode - 1], and the total cost is steps * costs[mode - 1]. Return [mode, totalTime, totalCost] for the mode with the smallest total time; break ties by smaller total cost. If no mode can reach the destination, return [-1, -1, -1].
Constraints
Movement is allowed in the four cardinal directions. The grid contains one S and one D.
Example 1
Input:
grid = ["S11","221","22D"]
times = [5,3,1,10]
costs = [1,3,1,1]
Output:
[2,12,12]
Explanation:
Mode 1 and mode 2 each need four steps, but mode 2 has lower total time: 4 * 3 = 12.
Example 2
Input:
grid = ["S11","224","33D"]
times = [2,2,2,2]
costs = [1,1,1,1]
Output:
[-1,-1,-1]
Explanation: No commute mode has a connected path from start to destination.
You are given two strings s and pattern. Find the starting index of the first substring of s that is an anagram of pattern.
If no substring of s is an anagram of pattern, return -1.
Two strings are anagrams if they contain the same characters with the same frequencies.
Function Description
Complete the function findFirstAnagramIndex in the editor below.
findFirstAnagramIndex has the following parameters:
String s: the search stringString pattern: the target anagram pattern Returnsint: the starting index of the first anagram, or-1if none exists.
Constraints
The source thread did not provide explicit numeric bounds.
- The anagram must be formed by a contiguous substring of
s. - If multiple answers exist, return the smallest starting index.
Example 1
Input:
s = "cbaebabacd"
pattern = "abc"
Output:
0
Explanation:
The substring "cba" starting at index 0 is an anagram of "abc", and it is the first such substring.
Example 2
Input:
s = "abab"
pattern = "ab"
Output:
0
Explanation:
The substring "ab" starting at index 0 is already an anagram of the pattern, so the first valid index is 0.
To view the original problem statement, pls check out the source image below Imagine you're navigating through a file system that has several storage compartments, each with a unique name—let's call them "buckets." You can move between these buckets and create files within them. Your task is to follow a series of commands and, at the end of the day, determine which bucket ended up holding the most files. Here is how the story unfolds: Move to a bucket: Whenever you're told to "goto" a certain bucket, you immediately jump to that bucket. You can assume that the bucket always exists, so there's no need to worry about getting lost.. Create a file: If you're in a bucket and receive a command to "create" a file, you simply add a new file with the specified name to that bucket. If a file with that name already exists in the current bucket, you skip the creation—no duplicates allowed. Your mission is to process all these commands one by one. At the end of all the instructions, your goal is to figure out which bucket contains the most files. You’re guaranteed that there won’t be any ties, so there will always be a clear winner. Here are some things to keep in mind: The very first command you get will always tell you to move to a specific bucket, so you’ll never start out lost. At least one of the commands will be about creating a file, so you’ll have some files to work with. Don’t worry too much about finding the most optimal way to do this; as long as your approach isn’t too slow, it will work just fine. Your final task is to identify the bucket that ended up with the most files after all the commands have been processed, and that’s the bucket you’ll declare as the winner!
Example 1
Input:
commands = ["goto bucketA", "create fileA", "create fileB", "create fileA", "goto bucketB", "goto bucketC", "create fileA", "create fileB", "create fileC"]
Output:
"bucketC"
Explanation: This explanation is just an educated guess. If you find anything wrong, pls dont hesitate to lmk! Many thanks in advance! For the given commands, the number of files in each bucket is as follows:
- bucketA: 2 files (fileA and fileB)
- bucketB: 0 files
- bucketC: 3 files (fileA, fileB, and fileC)
Since bucketC has the largest number of files, the output is
"bucketC".
Imagine that there are several lamps placed on a number line, each of which illuminates some segment of the line. Specifically, the lamps are represented in a two-dimensional array lamps, where the ith lamp covers the segment from lamps[i][0] to lamps[i][1], inclusive.
Additionally, you are given a list of control points on this number line, represented by an array points. Your task is to find the number of lamps that illuminate each control point. Specifically, for each control point points[i] in the array, your task is to find the number of lamps lamps[i] which include this point within its covered segment - when points[i] lies inside the segment [lamps[i][0], lamps[i][1]].
As a result, return an array of integers, where ith integer corresponds to the answer for the ith control point.
note - feel free to see the Problem Source at the bottom of the page for the original problem description :) Imagine you have two arrays of numbers, firstArray and secondArray, and your task is to discover the longest common prefix (LCP) that can be found between any pair of numbers, each from a different array. A prefix is formed by one or more digits starting from the leftmost digit of a number. For example, the number 123 has prefixes like 1, 12, and 123 itself. If you look at numbers 5645539 and 564554, their longest common prefix is 56455. However, if you compare 123 and 456, there is no common prefix at all. Your goal is to determine the length of the longest common prefix found between these two arrays, and if there isn't one, you'll simply return zero.
Constraints
1 ≤ firstArray.length ≤ 5 · 10⁴1 ≤ firstArray[i] ≤ 10⁹
Example 1
Input:
firstArray = [25, 288, 2655, 54546, 54, 555]
secondArray = [2, 255, 266, 244, 26, 5, 54547]
Output:
4
Explanation: The best pair is 54546 from the first array and 54547 from the second array with the LCP 5454, where 5454 is of length 4.
Example 2
Input:
firstArray = [25, 288, 2655, 544, 54, 555]
secondArray = [2, 255, 266, 244, 26, 5, 5444444]
Output:
3
Explanation: The best pair is 544 from the first array and 5444444 from the second array with the LCP 544, where 544 is of length 3.
Example 3
Input:
firstArray = [817, 99]
secondArray = [1999, 1909]
Output:
0
Explanation: No pair of numbers from different arrays has a common prefix, hence the answer is 0.
You are given a matrix of characters representing a board. Each cell of the matrix contains one of three characters:
"." which means that the cell is empty;
"*" which means that the cell contains an obstacle;
"#" which means that the cell contains a box.
You decide to do the following operations:
Firstly, you push the boxes to the right as far as possible, so each box moves right until it hits an obstacle, another box, or the right edge of the board.
Then, you push the boxes down as far as possible, so each box moves down until it hits an obstacle, another box, or the bottom of the board.
Given board, a matrix representation of the board, your task is to return the state of the board after the push and fall operations.
Note: You are not expected to provide the most optimal solution, but a solution with time complexity not worse than O(board.length * board[0].length * min(board.length, board[0].length)) will fit within the execution time limit.
Example 1
Input:
board = [['-', '#' , '-', '-' ,'-'], ['-', '-', '-', '-', '-'], ['#', '-', '#', '#', '-'], ['#', '-', '-', '-', '#']]
Output:
['-', '-' , '-', '-' ,'-'], ['-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-'], ['#', '-', '-', '-', '#']]
Explanation: After pushing the boxes to the right, the board state will be: [["#","#",".",".","",".",".","#","."], [".",".",".",".",".",".","",".","."], [".",".",".",".",".",".",".",".","."], ["#",".",".","#",".",".",".",".","#"]] After pushing the boxes down, the board state will be: [[".",".",".",".","",".",".",".","."], [".",".",".",".",".",".","",".","."], [".",".",".",".",".",".",".",".","."], ["#","#","#","#",".",".",".","#","#"]]
Example 2
Input:
board = [["#",".",".",".",".",".",".",".","."], [".","#",".",".",".",".",".",".","."], [".",".","#",".",".",".",".",".","."], [".",".",".","#",".",".",".",".","."], [".",".",".",".","#",".",".",".","."], [".",".",".",".",".","#",".",".","."], [".",".",".",".",".",".","#",".","."], [".",".",".",".",".",".",".","#","."], ["*","*","*","*","*","*","*","*","#"]]
Output:
[[".",".",".",".",".",".",".",".","."], [".",".",".",".",".",".",".",".","."], [".",".",".",".",".",".",".",".","."], [".",".",".",".",".",".",".",".","."], [".",".",".",".",".",".",".",".","."], [".",".",".",".",".",".",".",".","."], ["#",".",".",".",".",".",".",".","."], ["*","*","*","*","*","*","*","#","#"]]
Explanation: After pushing the boxes to the right, the board state will be: [["#",".",".",".",".",".",".",".","."], [".","#",".",".",".",".",".",".","."], [".",".","#",".",".",".",".",".","."], [".",".",".","#",".",".",".",".","."], [".",".",".",".","#",".",".",".","."], [".",".",".",".",".","#",".",".","."], [".",".",".",".",".",".","#",".","."], [".",".",".",".",".",".",".","#","."], ["","","","","","","","","#"]] After pushing the boxes down, the board state will be: [[".",".",".",".",".",".",".",".","."], [".",".",".",".",".",".",".",".","."], [".",".",".",".",".",".",".",".","."], [".",".",".",".",".",".",".",".","."], [".",".",".",".",".",".",".",".","."], [".",".",".",".",".",".",".",".","."], ["#",".",".",".",".",".",".",".","."], ["","","","","","","*","#","#"]]
You are given a string binaryString consisting of '0's and '1's, as well as an array of strings requests containing requests of two types:
requests[i] = "count:<index>" - find the number of '0's in binaryString before and including the specified 0-based index.
requests[i] = "flip" - flip all elements of binaryString, i.e. change every '0' to '1', and every '1' to '0'.
Return an array answers, where answers[i] contains the answer for the respective count request.
Example 1
Input:
binaryString = "1111010"
requests = ["count:4", "count:6", "flip", "count:4", "flip", "count:2"]
Output:
[1, 2, 4, 0]
Explanation:
Explnanation is an educated guess. If you find anythign wrong, pls feel free let me know! Manyyy thanks in advance!!
For binaryString = "1111010" and requests = ["count:4", "count:6", "flip", "count:4", "flip", "count:2"], the output should be solution(binaryString, requests) = [1, 2, 4, 0].
- After the first request "count:4", the number of '0's before and including index 4 is 1.
- After the second request "count:6", the number of '0's before and including index 6 is 2.
- After the "flip" request, the binaryString becomes "0000101".
- After the next "count:4" request, the number of '0's before and including index 4 is 4.
- Another "flip" request changes the binaryString back to "1111010".
- Finally, after the "count:2" request, the number of '0's before and including index 2 is 0.
note - feel free to see the Problem Source section below for the original problem description and example explanation ;) Imagine you have a list of numbers and a smaller list called pattern, which describes how the numbers should change. The pattern only contains three types of instructions: 1 means the next number should be larger than the previous one. 0 means the next number should be equal to the previous one. -1 means the next number should be smaller than the previous one. Your job is to find how many stretches of consecutive numbers in the big list follow this exact pattern. Just make sure the solution isn't too slow—though it doesn’t need to be perfect, it should work efficiently enough.
Example 1
Input:
numbers = [4, 1, 3, 4, 4, 5, 5, 1]
pattern = [1, 0, -1]
Output:
1
Explanation: Let’s explore some possible subarrays of length 3. We don't need to check the subarray starting at numbers[0]—there's no number before the first element to compare! Subarray [1, 3, 4] doesn’t match. The pattern starts with 1, meaning the first number should be larger than the one before it, but numbers[1] = 1 is less than numbers[0] = 4. Subarray [3, 4, 4] fails because the pattern says 0 for the second number, meaning it should stay the same, but numbers[3] = 4 is greater than numbers[2] = 3. Subarray [4, 4, 5] doesn’t work either. The pattern ends with -1, meaning the last number should be smaller than the previous one, but numbers[5] = 5 is greater than numbers[4] = 4. Subarray [4, 5, 5] also doesn’t match for the same reason. Finally, subarray [5, 5, 1] perfectly matches the pattern: numbers[5] > numbers[4], as the pattern starts with 1. numbers[6] = numbers[5], following the 0 in the pattern. numbers[7] < numbers[6], just as the pattern ends with -1. This subarray is the match we’re looking for!
note - see the Problem Source section at the vely bottom of the page for the original problem description :) Once upon a time, in a land of square matrices filled with 0's, 1's, and 2's, there was a magical n x n matrix, where n was always an odd number. The wise mathematicians wanted to transform this matrix to create a grand letter "L" that would rise majestically from the upper-left corner down to the center of the matrix and stretch horizontally to the right corner. The "L" was formed by 1's, while the surrounding areas would remain as 0's and 2's. The challenge was to figure out the minimum number of cells that needed to be changed to achieve this enchanting design, ensuring that all the cells making up the "L" glowed with the number 1, while the background continued to shimmer with the magic of 0's and 2's. Thus, the quest began to determine how many cells would need to be altered to bring this vision to life!
Constraints
5 ≤ matrix.length ≤ 990 ≤ matrix[i][j] ≤ 2
Example 1
Input:
matrix = [[1, 0, 2], [1, 2, 0], [0, 2, 0]]
Output:
2
Explanation: To achieve the magical "L," the wise mathematicians discovered that the best way was to transform the 1 in the 0th row into a 2, and the 1 in the 1st row into a 0. This clever move allowed the 2's to create the enchanting shape of the letter "Y," while the 0's gracefully formed the background, enhancing the beauty of the design. With these delightful changes, the final matrix emerged, shimmering with the perfect blend of numbers, showcasing the magnificent "L" in all its glory. matrix = [ [2, 0, 2], [0, 2, 0], [0, 2, 0], ]
Example 2
Input:
matrix = [[2, 0, 0, 0, 2], [1, 2, 1, 2, 0], [0, 1, 2, 1, 0], [1, 1, 2, 1, 1]]
Output:
8
Explanation: In this magical transformation, the 2's gracefully took shape to form the enchanting letter "Y." The wise mathematicians discovered that the best solution was to change all the 0's, a total of 8, into shimmering 1's, resulting in a grand total of 10 luminous 1's illuminating the matrix. With these clever adjustments, the final matrix emerged, radiating with the brilliance of the newly crafted "Y" and creating a mesmerizing display that captured the essence of their creative endeavor. matrix = [ [2, 1, 1, 1, 2], [1, 2, 1, 2, 1], [1, 1, 2, 1, 1], [1, 1, 2, 1, 1], [1, 1, 2, 1, 1], ]
There is an array of fruits. Your goal is to calculate the amount of distinct pairs (x, y) so that
0 ≤ x < y < length of fruits. Note that fruits[x] could be gotten from fruits[y] by swapping no more than
2 digits of fruits[y] :)
Note again:: One might not make swapping to any digits at all, so, if x < y and fruits[x] = fruits[y], such pair
should be counted.
Constraints
1 ≤ fruits.length ≤ 10⁴1 ≤ numbers[i] ≤ 10⁹
Example 1
Input:
fruits = [1, 23, 156, 1650, 651, 165, 32]
Output:
3
Explanation:
- fruist[1] = 23 could be gotten from fruits[6] = 32 just by swapping its only 2 digits :)
- fruist[2] = 156 could be gotten from fruits[4] = 651 just by swapping six and one :))
- fruist[2] = 156 could be gotten from fruits[5] = 165 just by swapping six & five :))
Example 2
Input:
fruits = [123, 321, 123]
Output:
3
Explanation:
- fruits[1] = 321 could be gotten from fruits[0] = 123, swapping one & three
- fruits[2] = 123 could be gotten from fruits[0] = 123, swapping nothing
- fruits[2] = 123 could be gotten from fruits[1] = 321, swapping three & one
解锁全部 23 道题的解法
题面你已经看到了 — 解法 + 三语代码 + 复杂度推导 + 边界讨论, Pro 解锁.
- 📚1000+ 道真实北美 OA, Python / Java / C++ 三语题解
- 📊个人 dashboard + 进度可视化 + 14 天活跃图
- 📝题目笔记跨设备同步 + 个人复盘库
- 🔓随时取消下次续费, Stripe Customer Portal 自助管理