OAmaster
— / 16已做

You are monitoring building density in a district of N positions (0..N-1), all initially occupied. queries is a sequence of positions to demolish (in order). After each removal, return the longest contiguous run of still-occupied positions as a list of those positions; ties broken by leftmost.

Example: N=5, queries=[2, 1, 3][[0, 1], [0, 1], [4]].

解法

用有序集合维护占用位置;每次移除后扫一遍有序位置找最长连续段。暴力 O(Q · N)N, Q ≤ 10⁵ 下足够。

def longestSegmentsAfterQueries(N: int, queries: list[int]) -> list[list[int]]:
    available = set(range(N))
    results = []
    for q in queries:
        available.discard(q)
        best_len, best_start = 0, -1
        cur_len, cur_start = 0, -1
        for p in sorted(available):
            if cur_start != -1 and p == cur_start + cur_len:
                cur_len += 1
            else:
                cur_len, cur_start = 1, p
            if cur_len > best_len:
                best_len, best_start = cur_len, cur_start
        results.append(list(range(best_start, best_start + best_len)) if best_len > 0 else [])
    return results
import java.util.*;

class Solution {
    static List<List<Integer>> longestSegmentsAfterQueries(int N, int[] queries) {
        TreeSet<Integer> available = new TreeSet<>();
        for (int i = 0; i < N; i++) available.add(i);
        List<List<Integer>> results = new ArrayList<>();
        for (int q : queries) {
            available.remove(q);
            int bestLen = 0, bestStart = -1, curLen = 0, curStart = -1;
            Integer prev = null;
            for (int p : available) {
                if (prev != null && p == prev + 1) curLen++;
                else { curLen = 1; curStart = p; }
                if (curLen > bestLen) { bestLen = curLen; bestStart = curStart; }
                prev = p;
            }
            List<Integer> seg = new ArrayList<>();
            for (int i = 0; i < bestLen; i++) seg.add(bestStart + i);
            results.add(seg);
        }
        return results;
    }
}
#include <vector>
#include <set>
using namespace std;

vector<vector<int>> longestSegmentsAfterQueries(int N, vector<int>& queries) {
 set<int> available;
 for (int i = 0; i < N; i++) available.insert(i);
 vector<vector<int>> results;
 for (int q : queries) {
 available.erase(q);
 int bestLen = 0, bestStart = -1, curLen = 0, curStart = -1;
 bool hasPrev = false; int prev = 0;
 for (int p : available) {
 if (hasPrev && p == prev + 1) curLen++;
 else { curLen = 1; curStart = p; }
 if (curLen > bestLen) { bestLen = curLen; bestStart = curStart; }
 prev = p; hasPrev = true;
 }
 vector<int> seg;
 for (int i = 0; i < bestLen; i++) seg.push_back(bestStart + i);
 results.push_back(seg);
 }
 return results;
}

Given an array numbers of length n and a positive integer k, find the number of contiguous subarrays for which there are at least k pairs of elements with duplicate values. A pair (i, j) with i < j is counted if numbers[i] == numbers[j].

Examples:

  • numbers = [0, 1, 0, 1, 0], k = 23
  • numbers = [2, 2, 2, 2, 2, 2], k = 31

解法

滑动窗口:右扩时把 cnt[x] 个新重复对加进 dup_pairsdup_pairs ≥ k 时收缩左端(先减 cnt[numbers[l]] 抵消贡献的对数)。收缩后以 r 结尾、起点在 [0..l-1] 的子数组都合法,ans += l。复杂度 O(n)

from collections import defaultdict

def countSubarrays(numbers: list[int], k: int) -> int:
    cnt = defaultdict(int)
    dup_pairs = 0
    l = 0
    ans = 0
    for r in range(len(numbers)):
        x = numbers[r]
        dup_pairs += cnt[x]
        cnt[x] += 1
        while dup_pairs >= k:
            cnt[numbers[l]] -= 1
            dup_pairs -= cnt[numbers[l]]
            l += 1
        ans += l
    return ans
import java.util.*;

class Solution {
    static long countSubarrays(int[] numbers, int k) {
        Map<Integer, Integer> cnt = new HashMap<>();
        long dup = 0, ans = 0;
        int l = 0;
        for (int r = 0; r < numbers.length; r++) {
            int x = numbers[r];
            dup += cnt.getOrDefault(x, 0);
            cnt.merge(x, 1, Integer::sum);
            while (dup >= k) {
                cnt.merge(numbers[l], -1, Integer::sum);
                dup -= cnt.get(numbers[l]);
                l++;
            }
            ans += l;
        }
        return ans;
    }
}
#include <vector>
#include <unordered_map>
using namespace std;

long long countSubarrays(vector<int>& numbers, int k) {
 unordered_map<int, int> cnt;
 long long dup = 0, ans = 0;
 int l = 0;
 for (int r = 0; r < (int)numbers.size(); r++) {
 int x = numbers[r];
 dup += cnt[x];
 cnt[x]++;
 while (dup >= k) {
 cnt[numbers[l]]--;
 dup -= cnt[numbers[l]];
 l++;
 }
 ans += l;
 }
 return ans;
}

A rhombic area of size r is the set of all cells whose Manhattan distance to a center cell is less than r. Given a rectangular matrix of integers matrix and an integer radius, for each cell c whose rhombic area of size radius fully fits within the matrix, sum the elements within that rhombus. Return the highest sum. Return 0 if no center fits.

Example: matrix = 6×6 grid of values, radius = 3 → highest rhombus sum (e.g. 35).

解法

枚举每个候选中心 (cr, cc)(菱形不越界),再遍历每格 (i, j),把 |cr - i| + |cc - j| < r 的累加。最坏 O(n²m²),小网格无压力。

def maxRhombicSum(matrix: list[list[int]], radius: int) -> int:
    n, m = len(matrix), len(matrix[0])
    best = 0
    found = False
    for cr in range(radius - 1, n - radius + 1):
        for cc in range(radius - 1, m - radius + 1):
            s = 0
            for i in range(n):
                for j in range(m):
                    if abs(cr - i) + abs(cc - j) < radius:
                        s += matrix[i][j]
            if not found or s > best:
                best = s; found = True
    return best
class Solution {
    static long maxRhombicSum(int[][] matrix, int radius) {
        int n = matrix.length, m = matrix[0].length;
        long best = 0;
        boolean found = false;
        for (int cr = radius - 1; cr < n - radius + 1; cr++)
            for (int cc = radius - 1; cc < m - radius + 1; cc++) {
                long s = 0;
                for (int i = 0; i < n; i++)
                    for (int j = 0; j < m; j++)
                        if (Math.abs(cr - i) + Math.abs(cc - j) < radius) s += matrix[i][j];
                if (!found || s > best) { best = s; found = true; }
            }
        return best;
    }
}
#include <vector>
#include <cstdlib>
using namespace std;

long long maxRhombicSum(vector<vector<int>>& matrix, int radius) {
 int n = matrix.size(), m = matrix[0].size();
 long long best = 0;
 bool found = false;
 for (int cr = radius - 1; cr < n - radius + 1; cr++)
 for (int cc = radius - 1; cc < m - radius + 1; cc++) {
 long long s = 0;
 for (int i = 0; i < n; i++)
 for (int j = 0; j < m; j++)
 if (abs(cr - i) + abs(cc - j) < radius) s += matrix[i][j];
 if (!found || s > best) { best = s; found = true; }
 }
 return best;
}

You are formatting text for a newspaper page. Text is provided as an array paragraphs, where each paragraph is an array of "chunks". Each chunk has the form [type, content]:

  • type = "p": paragraph (plain text)
  • type = "bold": bold
  • type = "italic": italic
  • type = "underline": underline

For each paragraph, return its formatted HTML-like string. Bold → <b>...</b>, italic → <i>...</i>, underline → <u>...</u>. Wrap the entire paragraph in <p>...</p>. Nested formatting should produce nested tags in the order they were applied.

Example: paragraphs = [[["bold", "Hello"]]]["<p><b>Hello</b></p>"].

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are monitoring building density in a district of houses on a number line. houses is an array of distinct integer positions, initially occupied. queries is a sequence of positions to demolish (in order); each is guaranteed to be in houses and distinct. After each removal, return the number of remaining contiguous house segments (a segment = one or more occupied positions with no occupied neighbor outside the segment).

Example: houses = [1, 2, 3, 6, 7, 9], queries = [6, 3, 7, 2, 9, 1][3, 3, 2, 2, 1, 0].

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given an array of positive integers a, count the number of pairs (i, j) with i < j and digitSum(a[i]) == digitSum(a[j]), where digitSum(x) is the sum of the decimal digits of x.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ a[i] ≤ 10⁹

Example 1

Input:

a = [3, 5, 1, 7, 8, 10, 62, 13]

Output:

5

Explanation: 数位和分桶:[3] sum 3;[5] sum 5;[1, 10] sum 1;[7, 7 from 16? no] sum 7 = 7;[8, 62, 17? no] sum 8 = 62;[10] sum 1;[13] sum 4。重新算:3→3, 5→5, 1→1, 7→7, 8→8, 10→1, 62→8, 13→4。配对:sum 1 有 10 即 1 对,sum 8 有 62 即 1 对。注:原题答案为 5 由完整源说明决定,此处实现以"数位和相等对数"为准。

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Plz check out the source image below for the original problem statement :)

Example 1

Input:

matrix = [[0, 0, 1, 2], [0, 2, 2, 2], [2, 1, 0, 1]]

Output:

3

Explanation: Just my educated guess. might be right might be wrong - The longest diagonal segment following the pattern 1, 2, 0, 2, 0, 2, 0, ... can be found starting from the element at row 2, column 1 (1-based index), going up and to the right. The segment is [1, 2, 0], which has a length of 3.

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given an array, find the numbers with t

Example 1

Input:

nums = [1, 9, 23, 30, 54, 103]

Output:

4

Explanation: The possible pairs with the same number of digits are:

  • {1, 9}
  • {23, 30}
  • {23, 54} There are a total of 4 different pairs, so the output is 4.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Implement a rate limiter that decides whether each incoming request should be allowed at a given timestamp. Each request contains a string key such as a user id, IP address, or API name, and a non-negative integer timestamp. Given a time window of length window seconds and a maximum limit limit, allow at most limit requests for the same key inside any valid window. For each request, return whether it is ALLOWed or REJECTed. Timestamps arrive in non-decreasing order. You may implement either a fixed-window or sliding-window policy, but the behavior must be consistent with the examples. Function Description Complete the function applyRateLimiter in the editor below. applyRateLimiter has the following parameters:

  • int window: the rate-limit window length in seconds
  • int limit: the maximum number of allowed requests per key in one window
  • String[] requests: each entry has the form "timestamp key" Returns String[]: one result per request, each being ALLOW or REJECT.

Constraints

  • 1 ≤ requests.length ≤ 2 * 10⁵
  • 1 ≤ window ≤ 10⁹
  • 1 ≤ limit ≤ 10⁵
  • Timestamps are non-negative integers in non-decreasing order.
  • Each request key contains no spaces.

Example 1

Input:

window = 10
limit = 2
requests = ["1 alice", "2 alice", "3 alice", "11 alice", "12 alice", "12 bob"]

Output:

["ALLOW", "ALLOW", "REJECT", "ALLOW", "ALLOW", "ALLOW"]

Explanation: The third request from alice arrives inside the same 10-second window as the first two and exceeds the limit. Later requests are evaluated against later windows.

Example 2

Input:

window = 5
limit = 1
requests = ["1 u", "1 u", "2 u", "6 u", "6 u"]

Output:

["ALLOW", "REJECT", "REJECT", "ALLOW", "REJECT"]

Explanation: Only one request per 5-second window is allowed for the same key in this example.

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given a list of strings data, where each string is in the form "$device_id, $usage_in_minutes", such that $device_id contains exactly five lowercase English letters ('a'-'z') and $usage_in_minutes contains exactly four digits, representing a positive integer between 1 and 1440 (possibly with leading zeros). For instance, "abxyz, 0010" describes $device_id = "abxyz" and $usage_in_minutes = 10 minutes. Given data, your task is to return the $device_id with the largest value of $usage_in_minutes. You may assume that all values of $device_id and $usage_in_minutes are both pairwise distinct in data.

Constraints

  • 1 ≤ data.length ≤ 1400
  • data[i].length = 10
  • device_id.length = 5
  • devide_id[i] ∈ ['a' - 'z']
  • usage_in_minutes.length = 4
  • 1 ≤ int(usage_in_minutes) ≤ 1400

Example 1

Input:

data = ["iqttt, 0077", "obvhd, 0093", "flohd, 0075"]

Output:

"obvhd"

Explanation: There are 3 devices, and the largest value of usage in minutes is 93 and it corresponds to devide with id "obvhd".

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

给一个整数数组 towers。每次操作可对任一塔加 1 或减 1,cost 为 1。求把数组改成"严格递增"或"严格递减"的最小总操作数。返回较小者。

Example 1

Input:

towers = [1, 4, 3, 2]

Output:

4

Explanation: The given array can be transformed into a valid strictly monotonic sequence at the cost shown.

Example 2

Input:

towers = [5, 7, 9, 4, 11]

Output:

9

Explanation: The given array can be transformed into a valid strictly monotonic sequence at the cost shown.

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Extend a basic rate limiter so that each request contains multiple fields such as userId, deviceId, or endpoint. Each field dimension has its own rule of the form fieldName window limit. For the same field value, allow at most limit requests inside a window of length window seconds. A request is ALLOWed only if it stays within the limit for every configured dimension. If any one dimension exceeds its limit, the request is REJECTed. Function Description Complete the function applyMultiFieldRateLimiter in the editor below. applyMultiFieldRateLimiter has the following parameters:

  • String[] fieldRules: each entry has the form "fieldName window limit"
  • String[] requests: each entry has the form "timestamp value1 value2 ..." in the same order as the field rules Returns String[]: one result per request, each being ALLOW or REJECT.

Constraints

  • 1 ≤ fieldRules.length ≤ 10
  • 1 ≤ requests.length ≤ 2 * 10⁵
  • Each field value contains no spaces.
  • Timestamps are non-decreasing.

Example 1

Input:

fieldRules = ["user 10 2", "device 10 3"]
requests = ["1 u1 d1", "2 u1 d1", "3 u1 d1", "4 u2 d1", "11 u1 d1", "12 u1 d1"]

Output:

["ALLOW", "ALLOW", "REJECT", "ALLOW", "ALLOW", "ALLOW"]

Explanation: The third request is rejected because the user dimension exceeds its limit even though the device dimension is still valid.

Example 2

Input:

fieldRules = ["user 5 1", "endpoint 3 2"]
requests = ["1 u1 /a", "2 u1 /a", "2 u2 /a", "4 u2 /a"]

Output:

["ALLOW", "REJECT", "ALLOW", "REJECT"]

Explanation: The second request fails the user rule, while the fourth request fails the endpoint rule because that endpoint already hit its limit in the active window.

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Note - the original problem description is in the problem source section below Imagine you’re in charge of scheduling a new meeting for a group of employees who have already packed their day with various appointments. The day is measured in minutes, starting from 0 (midnight) and ending at 1440 minutes (the very last moment of the day). Each employee’s busy schedule is laid out in a special array called schedules. In this array: schedules[i][j] tells you the exact start and end times of the jth meeting for the ith employee. Every meeting is represented as a pair of numbers: [startTime, finishTime]—both in minutes since the start of the day. You’ve been tasked with finding the earliest moment in this busy day where all employees are free to meet for a certain period of time, called length. But, there’s a catch! The new meeting needs to fit within the same day, meaning it can’t run past 1440 minutes (the end of the day). Your job is to sift through the employees’ schedules, find a time where everyone is available for this new meeting, and figure out the earliest possible time to set it. If there’s no such moment when all are free for that meeting, you’ll return -1, indicating that it’s impossible to schedule the meeting on this day. Don’t worry too much about finding the absolute most efficient solution—just make sure that your approach can handle the complexity of multiple busy schedules without taking too long.

Constraints

  • 1 ≤ schedules.length ≤ 100
  • ``0 ≤ schedules[i].length ≤ 100
  • ``schedules[i][j].length = 2
  • 0 ≤ schedules[i][j][0] < schedules[i][j][1] ≤ 1400
  • 1 ≤ length ≤ 24 * 60

Example 1

Input:

schedules = [[[60, 150], [180, 240]], [[0, 210], [360, 420]]]
length = 120

Output:

240

Explanation: see problem source below for details.

Example 2

Input:

schedules = [[[480, 510]], [[240, 330]], [[375, 400]]]
length = 180

Output:

0

Explanation: see problem source below for details. you are the best!

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Like alwasy, feel free to check out source images for original problem statement. Thank U for your understanding~~~~~~

Example 1

Input:

a = [13, 5604, 31, 2, 13, 4560, 546, 654, 456]

Output:

5

Explanation: There are 5 cyclic pairs of numbers - pairs which are equal to each other after cyclic shifts.

  • a[0] = 13 and a[4] = 13 (i = 0 and j = 4)
  • a[0] = 13 and a[4] = 13 (i = 0 and j = 4)
  • a[1] = 5604 and a[5] = 4560 (i = 1 and j = 5)
  • a[2] = 31 and a[4] = 13 (i = 2 and j = 4)
  • a[6] = 546 and a[7] = 654 (i = 6 and j = 7) Note that a[6] = 546 and a[8] = 456 are not cyclic pairs - 546 can only be paired with cyclic shift of 546, 465 and 654. Also, note that a[5] = 4560 and a[8] = 456 are not cyclic pairs because they have different number of digits.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given an array of strings words, find the number of pairs where either the strings are equal or one string ends with another. In other words, find the number of such pairs (i, j) (0 ≤ i < j < words.length) that words[i] is a suffix of words[j].

Constraints

  • 1 ≤ words.length ≤ 10⁵
  • 1 ≤ words[i].length ≤ 10

Example 1

Input:

words = ["hack", "hackhour", "jammon", "backgammon", "comeback", "come", "door"]

Output:

3

Explanation: The relevant pairs are:

  • words[0] = "hack" and words[1] = "comeback"
  • words[1] = "hackhour" and words[6] = "door"
  • words[2] = "jammon" and words[3] = "backgammon"

Example 2

Input:

words = ["cha", "a", "a", "b", "ba", "ca"]

Output:

8

Explanation: The relevant pairs are:

  • words[0] = "cha" and words[1] = "a"
  • words[0] = "cha" and words[2] = "a"
  • words[0] = "cha" and words[4] = "ba"
  • words[1] = "a" and words[2] = "a"
  • words[1] = "a" and words[4] = "ba"
  • words[1] = "a" and words[5] = "ca"
  • words[2] = "a" and words[4] = "ba"
  • words[2] = "a" and words[5] = "ca"
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Imagine you have two long lists of numbers, let’s call them a and b, and they are exactly the same length. Your goal is to find special pairs of positions, (i, j), where i is smaller than j, and something interesting happens between the numbers at these positions. For each pair, you’re looking for this magical balance: When you take the number from list a at position i and subtract the number from list b at position j, it should be equal to what you get when you take the number from list a at position j and subtract the number from list b at position i. Your task is to figure out how many such special pairs exist in these two lists.

Example 1

Input:

a = [2, -2, 5, 3]
b = [1, 5, -1, 1]

Output:

6

Explanation: see the problem source section below for the original explanation ;)

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁
Pro 会员

解锁全部 13 道题的解法

题面你已经看到了 — 解法 + 三语代码 + 复杂度推导 + 边界讨论, Pro 解锁.

Pro 解锁全部
  • 📚1000+ 道真实北美 OA, Python / Java / C++ 三语题解
  • 📊个人 dashboard + 进度可视化 + 14 天活跃图
  • 📝题目笔记跨设备同步 + 个人复盘库
  • 🔓随时取消下次续费, Stripe Customer Portal 自助管理
$12/月($98/年, 一次付清省 32%)

≈ 北美 SWE 工资 10 分钟 · LeetCode Premium $35/月 的 23%