OAmaster
— / 32已做

Imagine a gravity-based puzzle game where an irregular figure made of * cells must fall to the bottom of board. Cells are '-' (empty), '#' (obstacle), or '*' (figure). Find the minimum number of '#' obstacles to remove so the figure can touch the bottom row with at least one of its cells. The figure is one connected piece.

  • 1 ≤ board.length ≤ 100
  • 1 ≤ board[0].length ≤ 100
  • board[i][j]{'-', '#', '*'}
  • Execution time limit: 3 seconds
  • Memory limit: 1 GB
board = [['*', '*', '*'],
 ['#', '*', '#'],
 ['*', '-', '-'],
 ['-', '-', '-'],
 ['-', '#', '-']]
solution(board) = 2

解法

每一列上图形会下落直到最底部的 * 触地。该列的代价 = 该最底 * 严格下方的 # 数。整个图形能下落的距离受最受限列约束,答案 = 所有列代价的最小值。复杂度 O(rows × cols)

def solution(board: list[list[str]]) -> int:
    rows, cols = len(board), len(board[0])
    ans = float('inf')

    for c in range(cols):
        # 找到该列最底下的 '*' 行号
        bottom_star = -1
        for r in range(rows):
            if board[r][c] == '*':
                bottom_star = r
        if bottom_star == -1:
            continue  # 这一列没有图形格子,跳过

        # 数从 bottom_star + 1 到 rows - 1 之间 '#' 的个数
        obstacles = 0
        for r in range(bottom_star + 1, rows):
            if board[r][c] == '#':
                obstacles += 1
        ans = min(ans, obstacles)

    return ans if ans != float('inf') else 0
class Solution {
    int solution(char[][] board) {
        int rows = board.length, cols = board[0].length;
        int ans = Integer.MAX_VALUE;

        for (int c = 0; c < cols; c++) {
            // 找到该列最底下的 '*' 行号
            int bottomStar = -1;
            for (int r = 0; r < rows; r++) {
                if (board[r][c] == '*') bottomStar = r;
            }
            if (bottomStar == -1) continue;

            // 数从 bottomStar + 1 到 rows - 1 之间 '#' 的个数
            int obstacles = 0;
            for (int r = bottomStar + 1; r < rows; r++) {
                if (board[r][c] == '#') obstacles++;
            }
            ans = Math.min(ans, obstacles);
        }
        return ans == Integer.MAX_VALUE ? 0 : ans;
    }
}
class Solution {
public:
    int solution(vector<vector<char>>& board) {
        int rows = board.size(), cols = board[0].size();
        int ans = INT_MAX;

        for (int c = 0; c < cols; c++) {
            // 找到该列最底下的 '*' 行号
            int bottomStar = -1;
            for (int r = 0; r < rows; r++) {
                if (board[r][c] == '*') bottomStar = r;
            }
            if (bottomStar == -1) continue;

            // 数从 bottomStar + 1 到 rows - 1 之间 '#' 的个数
            int obstacles = 0;
            for (int r = bottomStar + 1; r < rows; r++) {
                if (board[r][c] == '#') obstacles++;
            }
            ans = min(ans, obstacles);
        }
        return ans == INT_MAX ? 0 : ans;
    }
};

Given readings, count how many entries are an integer power of k (i.e. k⁰, , , ...).

  • 1 ≤ readings.length ≤ 10⁵
  • 1 ≤ readings[i] ≤ 10⁹
  • 2 ≤ k ≤ 10⁹
  • Memory limit: 1 GB
solution([1, 2, 3, 8, 16, 10, 120], 2) = 5
solution([10000, 100, 1000000, 101, 1010, 1010000], 10) = 3

解法

把所有 ≤ max(readings)k 的幂存入哈希集合,每次读数 O(1) 查表。复杂度 O(n + log_k(maxVal))

def solution(readings: list[int], k: int) -> int:
    # 预生成所有 ≤ 1e9 的 k 的幂
    max_val = max(readings)
    powers = set()
    p = 1                                   # k⁰
    while p <= max_val:
        powers.add(p)
        # 防止 p * k 溢出(Python 没有 int 溢出,但仍要避免无意义的大数)
        if p > max_val // k and p * k > max_val:
            break
        p *= k

    return sum(1 for x in readings if x in powers)
import java.util.HashSet;
import java.util.Set;

class Solution {
    int solution(int[] readings, int k) {
        // 预生成所有 ≤ 1e9 的 k 的幂
        int maxVal = 0;
        for (int x : readings) maxVal = Math.max(maxVal, x);

        Set<Long> powers = new HashSet<>();
        long p = 1L;                        // k⁰;用 long 防溢出
        while (p <= maxVal) {
            powers.add(p);
            if (p > Long.MAX_VALUE / k) break;
            p *= k;
        }

        int count = 0;
        for (int x : readings) {
            if (powers.contains((long) x)) count++;
        }
        return count;
    }
}
#include <unordered_set>
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    int solution(vector<int>& readings, int k) {
        // 预生成所有 ≤ maxVal 的 k 的幂
        int maxVal = *max_element(readings.begin(), readings.end());

        unordered_set<long long> powers;
        long long p = 1;                    // k⁰;用 long long 防溢出
        while (p <= maxVal) {
            powers.insert(p);
            if (p > LLONG_MAX / k) break;
            p *= k;
        }

        int count = 0;
        for (int x : readings) {
            if (powers.count((long long) x)) count++;
        }
        return count;
    }
};

Given numbers and a pattern of {-1, 0, 1} (less / equal / greater than previous), count how many length-(m+1) subarrays of numbers match the pattern, where each consecutive pair's sign relation matches pattern[j].

  • 2 ≤ numbers.length ≤ 10⁴
  • 1 ≤ pattern.length < numbers.length
  • −10⁹ ≤ numbers[i] ≤ 10⁹
  • pattern[i]{-1, 0, 1}
  • Execution time limit: 4 seconds
  • Memory limit: 1 GB
numbers = [1, 4, 4, 1, 3, 5, 5, 3]
pattern = [1, 0, -1]
solution(numbers, pattern) = 2
startsubarraysignsmatch
0[1, 4, 4, 1]+, =, -1, 0, -1yes
1[4, 4, 1, 3]=, -, +0, -1, 1no
2[4, 1, 3, 5]-, +, +-1, 1, 1no
3[1, 3, 5, 5]+, +, =1, 1, 0no
4[3, 5, 5, 3]+, =, -1, 0, -1yes

解法

枚举长度为 m+1 的窗口起点 i。对 j ∈ [0, m) 比较 numbers[i+j+1]numbers[i+j],检查符号是否匹配 pattern[j]。复杂度 O((n - m) · m)

def solution(numbers: list[int], pattern: list[int]) -> int:
    n, m = len(numbers), len(pattern)
    count = 0

    # 枚举每个长度 m+1 的子数组起点
    for i in range(n - m):
        ok = True
        for j in range(m):
            diff = numbers[i + j + 1] - numbers[i + j]
            # diff 的正负号必须与 pattern[j] 一致
            if pattern[j] == 1 and diff <= 0:
                ok = False
                break
            if pattern[j] == 0 and diff != 0:
                ok = False
                break
            if pattern[j] == -1 and diff >= 0:
                ok = False
                break
        if ok:
            count += 1

    return count
class Solution {
    int solution(int[] numbers, int[] pattern) {
        int n = numbers.length, m = pattern.length;
        int count = 0;

        // 枚举每个长度 m+1 的子数组起点
        for (int i = 0; i <= n - m - 1; i++) {
            boolean ok = true;
            for (int j = 0; j < m; j++) {
                int diff = numbers[i + j + 1] - numbers[i + j];
                // diff 的正负号必须与 pattern[j] 一致
                if (pattern[j] == 1 && diff <= 0) { ok = false; break; }
                if (pattern[j] == 0 && diff != 0) { ok = false; break; }
                if (pattern[j] == -1 && diff >= 0) { ok = false; break; }
            }
            if (ok) count++;
        }
        return count;
    }
}
class Solution {
public:
    int solution(vector<int>& numbers, vector<int>& pattern) {
        int n = numbers.size(), m = pattern.size();
        int count = 0;

        // 枚举每个长度 m+1 的子数组起点
        for (int i = 0; i + m < n; i++) {
            bool ok = true;
            for (int j = 0; j < m; j++) {
                long long diff = (long long) numbers[i + j + 1] - numbers[i + j];
                // diff 的正负号必须与 pattern[j] 一致
                if (pattern[j] == 1 && diff <= 0) { ok = false; break; }
                if (pattern[j] == 0 && diff != 0) { ok = false; break; }
                if (pattern[j] == -1 && diff >= 0) { ok = false; break; }
            }
            if (ok) count++;
        }
        return count;
    }
};

Given each employee's busy time blocks schedules[i] (flat pair list of [start, finish] in minutes since 00:00) and a required length, find the earliest minute when ALL employees can attend a meeting of that length within the 24-hour day. Return -1 if impossible.

  • 1 ≤ schedules.length ≤ 100
  • 0 ≤ schedules[i][j] ≤ 1440
  • 1 ≤ length ≤ 1440
  • Execution time limit: 4 seconds
  • Memory limit: 1 GB
schedules = [
 [180, 240, 720, 900],
 [0, 60, 540, 600],
 [330, 360, 540, 600]
]
length = 120
solution(schedules, length) = 240
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given salesData and frequencyThreshold, find the length of the longest contiguous subarray in which at least one value appears strictly more than frequencyThreshold times.

  • 1 ≤ salesData.length ≤ 10⁵
  • 0 ≤ salesData[i] ≤ 10⁹
  • 1 ≤ frequencyThresholdsalesData.length
  • Execution time limit: 4 seconds
  • Memory limit: 1 GB
salesData = [1, 1, 1, 2, 3, 1, 1]
frequencyThreshold = 3
solution(salesData, frequencyThreshold) = 6
salesData = [1, 2, 3, 2, 3, 4, 1]
frequencyThreshold = 1
solution(salesData, frequencyThreshold) = 6
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Each object has a square collision box of side 2 centered at centers[i] = [x, y]. Two objects collide iff |x_A - x_B| ≤ 1 and |y_A - y_B| ≤ 1 (Chebyshev distance ≤ 1, edge-touch counts). Count the colliding pairs.

  • 1 ≤ centers.length ≤ 10³
  • −10⁴ ≤ centers[i][j] ≤ 10⁴
  • Execution time limit: 3 seconds
  • Memory limit: 1 GB
centers = [[0, 0], [1, 1], [2, 0], [0, 2]]
solution(centers) = 3
|x_A - x_B| ≤ 1 and |y_A - y_B| ≤ 1
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given a string message, shift each vowel (a, e, i, o, u) to the position of the next vowel in the string; the last vowel cycles to the first vowel's position. Non-vowel characters keep their position.

  • 1 ≤ message.length ≤ 1000
  • Execution time limit: 4 seconds(py3)
  • Memory limit: 1 GB
solution("codesignal") = "cadosegnil"
solution("plain text") = "plean tixt"
solution("some message with punctuatin marks, e.g. commas, dots, etc.")
 = "semo messege wath pancteatin morks, e.g. cemmos, dots, etc."
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Process queries of new house positions one by one. After each insertion, return the length of the currently longest run of consecutive occupied positions on the integer number line.

  • 1 ≤ queries.length ≤ 10⁵
  • 0 ≤ queries[i] ≤ 10⁹
  • Execution time limit: 4 seconds
  • Memory limit: 1 GB
queries = [2, 1, 4]
solution(queries) = [1, 2, 2]
queries = [1, 3, 0, 4]
solution(queries) = [1, 1, 2, 2]
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Apply a sequence of commands to matrix. Supported ops: swapRows r1 r2, swapColumns c1 c2, reverseRow r, reverseColumn c, rotate90Clockwise. Return the final matrix.

  • 1 ≤ commands.length ≤ 100
  • 0 ≤ matrix[i][j] ≤ 10⁹
  • Execution time limit: 4 seconds
  • Memory limit: 1 GB
matrix = [[1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]]
commands = ["swapRows 0 2", "swapColumns 1 2", "reverseRow 0", "reverseColumn 2", "rotate90Clockwise"]
solution(matrix, commands) = [[3, 4, 1],
 [5, 6, 2],
 [9, 8, 7]]
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given inclusive range [left, right] where 100 ≤ left ≤ right ≤ 999, count three-digit integers whose hundreds, tens, and units digits are pairwise distinct.

  • 100 ≤ leftright ≤ 999
  • Execution time limit: 3 seconds(java)
  • Memory limit: 1 GB
solution(476, 979) = 5
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Implement a simplified banking system. The full problem comes in four progressive levels — each level adds new operations on top of the previous one. All operations carry a timestamp parameter (milliseconds, strictly ascending across calls, range 1 to 10⁹).

Level 1 — accounts, deposits, transfers

  • boolean createAccount(int timestamp, String accountId) — create the account if it does not already exist. Returns true on success, false if accountId already exists.
  • Optional<Integer> deposit(int timestamp, String accountId, int amount) — credit amount to accountId. Returns the new balance, or Optional.empty() if the account does not exist.
  • Optional<Integer> transfer(int timestamp, String sourceAccountId, String targetAccountId, int amount) — move amount from source to target. Returns the source balance after the transfer, or Optional.empty() if either account is missing, the two ids are equal, or the source has insufficient funds.

Level 2 — outgoing ranking

  • List<String> topSpenders(int timestamp, int n) — return the top n accounts by total outgoing money (transfers out plus pay-withdrawals introduced in Level 3; cashback refunds do NOT count). Sort by outgoing descending, ties broken by accountId ascending. Format each entry "<accountId>(<totalOutgoing>)". If fewer than n accounts exist, return all of them.

Level 3 — scheduled payments with 2% cashback

  • Optional<String> pay(int timestamp, String accountId, int amount) — withdraw amount. On success return "payment<k>" where k is the 1-indexed global withdrawal counter. The withdrawal triggers a cashback of floor(amount * 0.02) that is refunded to the same account at exactly timestamp + 86_400_000 (24 hours later). At any timestamp, due cashback refunds must be applied BEFORE the operation at that timestamp runs. Returns Optional.empty() if the account is missing or has insufficient funds. Withdrawals count toward topSpenders totals; cashback refunds do not.
  • Optional<String> getPaymentStatus(int timestamp, String accountId, String payment) — return "IN_PROGRESS" or "CASHBACK_RECEIVED". Returns Optional.empty() if the account does not exist, the payment id does not exist, or the payment belongs to a different account.

Level 4 — merging accounts and historical balance

  • boolean mergeAccounts(int timestamp, String accountId1, String accountId2) — merge accountId2 into accountId1. After the merge accountId2 is removed. accountId1 inherits the balance, the outgoing total (for topSpenders), the pending cashbacks (refunded to accountId1 when due), and the payment-status lookup for accountId2's payment ids. Returns false if the two ids are equal or either is missing.
  • Optional<Integer> getBalance(int timestamp, String accountId, int timeAt) — return the balance of accountId at the moment immediately after the operation at timeAt finished. If the account did not exist at timeAt (either not yet created or already merged away), return Optional.empty(). A merged-away account's history transfers to the surviving account.

Execution time limit 20 s, memory limit 4 GB.

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

On an infinite number line, place obstacles and check if blocks fit without interference. Two operation types:

  • [1, x] places an obstacle at coordinate x (guaranteed empty when placed).
  • [2, x, size] checks whether a block of the given size can occupy [x, x + size) (i.e. positions x, x+1, …, x+size-1) with no obstacle present. Returns 1 if clear, 0 otherwise. This operation only checks feasibility; it does not place the block.

Given an array of operations, return a binary string with the results of all [2, ...] checks in order.

Example 1

Input:

operations = [[1, 2], [1, 5], [2, 3, 2], [2, 3, 3], [2, 1, 1], [2, 1, 2]]

Output:

"1010"

Explanation: Let's consider all operations:

  • [1, 2] - builds an obstacle at coordinate 2.
  • [1, 5] - builds an obstacle at coordinate 5.
  • [2, 3, 2] - checks and returns "1" as it is possible to build a block occupying coordinates 3 and 4.
  • [2, 3, 3] - checks and returns "0" as it is not possible to build a block occupying coordinates 3, 4, and 5.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

For every input string, count uppercase and lowercase letters and return the difference upper − lower. Positive means uppercase dominates, negative means lowercase does. Non-letter characters are ignored.

Constraints

  • 0 ≤ typedText.length ≤ 100.

Example 1

Input:

text = "CodeSignal"

Output:

-6

Explanation: In the given text, there are 2 uppercase letters ('C' and 'S') and 8 lowercase letters ('o', 'd', 'e', 'S', 'i', 'g', 'n', 'a', 'l'). This results in a difference of 2 - 8 = -6.

Example 2

Input:

text = "a"

Output:

-1

Explanation: The text contains just 1 lowercase letter ('a') and no uppercase letters. So, the difference is 0 - 1 = -1.

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

LC 498~ The other question was LC 1539~~ Given an m × n matrix mat, return an array of all the elements of the array in a diagonal order.

Constraints

  • m == mat.length
  • n == mat[i].length
  • `1

Example 1

Input:

mat = [[1,2,3],[4,5,6],[7,8,9]]

Output:

[1,2,4,7,3,5,8,6,9]

Explanation: Traverse the matrix diagonally as follows:

  • Start from element 1
  • Move up-right to reach 2, then down-left to 4
  • Move up-right to reach 7, then down-right to 3
  • Continue the pattern to traverse all elements diagonally The resulting diagonal order is [1,2,4,7,3,5,8,6,9].

Example 2

Input:

mat = [[1,2],[3,4]]

Output:

[1,2,3,4]

Explanation: Traverse the matrix diagonally as follows:

  • Start from element 1
  • Move up-right to reach 2, then down-left to 3
  • Finally, move up-right to reach 4 The resulting diagonal order is [1,2,3,4].
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given a matrix of integers, find all local maxima. An element is a local maximum if it is non-zero and no greater or equal element exists within its defined region.

The region for matrix[i][j] = v is the square centered at (i, j) with side 2v + 1, excluding the four corner cells. For example, if matrix[2][2] = 2, the region is a 5×5 square minus its 4 corners. If the region exceeds matrix bounds, evaluate only the in-bounds portion.

Return a 2D array of [row, col] coordinates of all local maxima, sorted first by row, then by column. Target complexity O(matrix.length² · matrix[0].length²).

Example 1

Input:

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

Output:

[[0, 0], [2, 2]]

Explanation:

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

Find and return a pair of integers in a sorted array (all integers are positive) that, when summed up, bring you the closest to the value of k. Example Input: [5, 8, 14, 17, 25, 40, 43] k: 35 Expected Output: (8, 25) since 8 + 25 = 33 which is closest to 35 (sum could be equals to, smaller or larger than k) Function Description Complete the function findPairClosestToK in the editor. findPairClosestToK has the following parameters:

    1. int[] arr: a sorted array of integers
    1. int k: the target sum Returns int[]: an array of two integers that are closest to the target sum k The other question was ~~
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Based on the source, the other question being asked was - Given an array of positive integers and target, return True if sum of continues array equal to target. A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array. You must write an algorithm that runs in O(log n) time.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • -2³¹ ≤ nums[i] ≤ 2³¹ - 1
  • nums[i] ≠ nums[i + 1] for all valid i.

Example 1

Input:

nums = [1,2,3,1]

Output:

2

Explanation: 3 is a peak element and your function should return the index number 2.

Example 2

Input:

nums = [1,2,1,3,5,6,4]

Output:

5

Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.

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

LC 1539~ The other question was LC 498~~ Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. Return the kth positive integer that is missing from this array. Function Description Complete the function findKthPositive in the editor. findKthPositive has the following parameters:

    1. int[] arr: an array of integers
    1. int k: an integer Returns int: the kth missing positive integer Constraints
  • `1 Follow up Could you solve this problem in less than O(n) complexity?
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's. (Same as LC 1004.) Function Description Complete the function longestOnes in the editor. longestOnes has the following parameters:

    1. int[] nums: a binary array
    1. int k: the maximum number of 0's that can be flipped Returns int: the maximum number of consecutive 1's

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • nums[i] is either 0 or 1.
  • 0 ≤ k ≤ nums.length
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given three integer arrays that are each sorted in non-decreasing order. Merge the arrays into one sorted array and remove duplicate values. Return the merged array in non-decreasing order. Function Description Complete the function mergeThreeSortedArrays in the editor. mergeThreeSortedArrays has the following parameters:

  • int a[]: the first sorted array
  • int b[]: the second sorted array
  • int c[]: the third sorted array Returns int[]: the sorted merged array with duplicates removed

Constraints

  • Each input array is sorted in non-decreasing order.
  • The arrays may contain duplicate values.
  • The arrays may be empty.

Example 1

Input:

a = [1, 3, 5]
b = [1, 2, 5, 6]
c = [2, 4, 6]

Output:

[1, 2, 3, 4, 5, 6]

Explanation: After merging all values and removing duplicates, the sorted result is [1, 2, 3, 4, 5, 6].

Example 2

Input:

a = []
b = [0, 0, 1]
c = [1, 2]

Output:

[0, 1, 2]

Explanation: Empty arrays are allowed. Duplicate 0 and 1 values are returned once.

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

As we can see from the source image, this question is from LC339 :) The other question asked together was LC636 :) You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. The depth of an integer is the number of lists that it is inside of. For example, the nested list [1,[2,2],[[3],2],1] has each integer's value set to its depth. Return the sum of each integer in nestedList multiplied by its depth.

Constraints

  • 1 ≤ nestedList.length ≤ 50
  • The values of the integers in the nested list is in the range [-100, 100].
  • The maximum depth of any integer is less than or equal to 50.

Example 1

Input:

nestedList = [[1,1],2,[1,1]]

Output:

10

Explanation: Four 1's at depth 2, one 2 at depth 1. 1*2 + 1*2 + 2*1 + 1*2 + 1*2 = 10.

Example 2

Input:

nestedList = [1,[4,[6]]]

Output:

27

Explanation: One 1 at depth 1, one 4 at depth 2, and one 6 at depth 3. 1*1 + 4*2 + 6*3 = 27.

Example 3

Input:

nestedList = [0]

Output:

0

Explanation: There is one 0 at depth 1. 0*1 = 0.

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

Given a string message and an integer n, replace every n-th consonant with the next consonant in alphabetical order, preserving case (e.g., 'b' → 'c', 'x' → 'y', 'Z' → 'B'). The consonant order is b c d f g h j k l m n p q r s t v w x y z; 'z'/'Z' wraps to 'b'/'B'. Target complexity O(|message|²) or better.

Example 1

Input:

message = "CodeSignal"
n = 3

Output:

"CodeTignam"

Explanation:

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

Given an integer array nums and windowSize, return the list of averages of every contiguous window of length windowSize. If windowSize > len(nums), return an empty list.

Example 1

Input:

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
windowSize = 7

Output:

[4.0, 5.0, 6.0]

Explanation: Three length-7 windows produce averages 4.0 (sum 28), 5.0 (sum 35), 6.0 (sum 42).

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

给两个数组 departingreturning,表示对应日期的去程票价和返程票价。选择一对 (i, j) 出发与返回,返回最小总花费 departing[i] + returning[j]

Example 1

Input:

departing = [1, 2, 3, 4]
returning = [4, 3, 2, 1]

Output:

2

Explanation: min(departing) = 1 (index 0) plus min(returning) = 1 (index 3), total 2.

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

In a bustling town where buses shuttle passengers throughout the day, the schedule of bus departures is meticulously recorded. Imagine you're standing at the bus stop, checking the time on your watch. You want to know how long ago the last bus departed. But if the day hasn't started yet and the first bus hasn't left, you're out of luck and receive a signal of -1. Your task is to determine, from the listed departure times and the current time, how many minutes have passed since the last bus departed. Remember, if a bus is scheduled to leave exactly at the current time, it hasn't departed yet.

Constraints

Uknown for now

Example 1

Input:

timeTable = ["12:30", "14:00", "19:55"]
moment = "14:30"

Output:

30

Explanation: The present moment is "14:30". The last bus departed at "14:00", so return 30 (30 minutes ago).

Example 2

Input:

timeTable = ["00:00", "14:00", "19:55"]
moment = "00:00"

Output:

-1

Explanation: Unfortunately , there is not buses departed before "00:00" (the bus was supposed to depart at "00:00" hasn't departed yet), so return -1; P.S. For original prompt, pls refer to source image.

Example 3

Input:

timeTable = ["12:30", "14:00", "19:55"]
moment = "14:00"

Output:

90

Explanation: The present moment is "14:00". And the most recent bus departed at "12:30" (the bus was supposed to go at "14:00" hasn't departed yet), so we return 90. P.S. For original prompt, pls refer to source image.

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

Embark on a perilous adventure with a group of brave explorers as they venture into the unknown depths of a mysterious cave! The cave is divided into a rectangular map with N rows and M columns, representing treacherous levels and chambers. The explorers' quest begins at the entrance (0, 0) and their ultimate goal is to reach the exit in the farthest corner (N-1, M-1). As they navigate through the cave, they'll encounter chambers marked with '!' which are safe to explore, and others marked with 'x' which are treacherous and impossible to pass through due to debris and danger. The explorers can move left, right, or climb down to the next level, but beware - climbing up is too risky, and they can never re-enter a chamber they've already visited! Their mission is to explore as many chambers as possible without backtracking or entering unsafe areas outside the map. If they can't reach the exit, the expedition will be canceled due to safety concerns. Can you help the explorers chart their course and find the maximum number of chambers they can explore on their journey to the exit? If not, return -1 to cancel the expedition. See "Problem Source" below for reference

Constraints

N/A

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

Imagine you're on a journey along the path of numbers, starting from your current location marked by an integer N. Your goal is to find the nearest landmark, which happens to be a Fibonacci number. But before you can reach it, you must determine the distance you need to travel to get there. Your task is to calculate this distance and return it as another integer. Function Description Complete the function closestLandMark in the editor . closestLandMark has the following parameter:

  • int aNum: an integer number Returns int: the distance to the closest "land mark". Memo: For original prompt, pls refer to source image

Constraints

0 ≤ N ≤ 1,000,000

Example 1

Input:

aNum = 25

Output:

4

Explanation: No explanation provided for now. Will add once find it :)

Example 2

Input:

aNum = 5

Output:

0

Explanation: No explanation provided for now. Will add once find it :)

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

Imagine you have two vectors of intervals, labeled as X and Y, each representing a series of segments along a path. In vector X, there are no overlapping segments, and the same goes for vector Y. Your task is to merge these two vector into a single vector, ensuring that there are no overlaps in the resulting segments. However, you're asked to devise a highly efficient solution that outperforms naive methods. Function Description Complete the function combineTwoVectorsOfIntervals in the editor . Returns int[][]: The merged vector of intervals without any overlaps. P.S. For original prompt, pls refer to source image.

Constraints

An unknown myth for now

Example 1

Input:

X = [[1,5], [10,14], [16,18]]
Y = [[2,6], [8,10], [11,20]]

Output:

[[1,6], [8,20]]

Explanation: The intervals from list X and list Y are merged and the overlapping intervals are combined to produce the following output:

  • The intervals [1,5] and [2,6] overlap and can be merged into [1,6].
  • The intervals [10,14] and [11,20] overlap with [8,10], and all can be merged into [8,20].
  • The interval [16,18] is within the bounds of [11,20] and is therefore already covered by it. The resulting merged list of intervals with no overlaps is [[1,6], [8,20]]. (Provided by Groot with from the west coast. PLS dont hesitate to correct me if you find anything wrong. I am always on the discord serva )
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Note - See the problem source section below for the original prompt :) 2000 years ago, in the enchanted land of Numeria, the Numerian Council was tasked with counting a special group of three-digit numbers that lived between left and right, where 100 ≤ left ≤ right ≤ 999. These numbers were unique because each of their three digits was distinct—like three adventurous friends on a quest, none of them alike. The council had to ensure they found all such numbers where no two digits were the same, within the magical range of Numeria. The task did not require the swiftest method, but it needed a solution that wouldn't take longer than right² steps, making sure the story of these numbers could be told efficiently without too much trouble. And so, their journey to count these special heroes began, celebrating each distinct number as a unique part of their magical land.

Constraints

  • 1 ≤ l ≤ r ≤ 10⁹
  • r - l ≤ 10⁵ (so we can iterate range)

Example 1

Input:

l = 876
r = 890

Output:

3

Explanation: In the enchanted land of Numeria, within the chosen range, three brave numbers stood out from the rest: 876, 879, and 890. These numbers were unlike any others, for each of their digits was pairwise distinct, just like three unique characters on an epic adventure. No digit repeated itself, and together they formed a trio that shone brightly in Numeria’s magical landscape, celebrating their special uniqueness in a way no other numbers could.

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

Imagine you have an bucket of numbers, each representing a character in a story. Now, imagine each character can be duplicated, like twins in a tale. Your task is to count how many sequences of characters in the story contain at least a certain number of pairs of twins. In other words, you're looking for segments of the story where you can find enough pairs of characters that appear twice within that segment. These pairs must be distinct from each other and should occur at different points in the story.

Constraints

Uknown for now

Example 1

Input:

bucket = [0, 1, 0, 1, 0]
n = 2

Output:

3

Explanation: Three sub-buckets contain at least n = 2 duplicate pairs:

  • bucket[0..3] = [0, 1, 0, 1]: pair of 0s (idx 0, 2) and pair of 1s (idx 1, 3).
  • bucket[1..4] = [1, 0, 1, 0]: pair of 1s (idx 1, 3) and pair of 0s (idx 2, 4).
  • bucket[0..4] = [0, 1, 0, 1, 0]: three 0s and two 1s — at least 2 pairs.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Note - See the problem source section below for the original prompt 5000 years agooo, in the magical land of Arithma, there existed an enchanted array called numbers, filled with special integers, and a mystical scroll called pattern that held the secret to finding certain relationships among the numbers. The pattern contained only 1, -1, or 0, each symbol representing a unique bond: 1 meant the current number must be greater than the previous one, -1 meant it must be smaller, and 0 indicated equality, like friends standing together unchanged. The council of Arithma sought to discover how many subarrays within numbers matched this magical pattern. They knew that numbers was longer than pattern, and they weren't seeking the swiftest way, but rather one that required at most numbers.length * pattern.length steps, enough to uncover all matching subarrays and reveal the hidden tales within.

Example 1

Input:

numbers = [4, 1, 3, 4, 4, 5, 5 ,1]
pattern = [1, 0, -1]

Output:

1

Explanation: Unfortunatelly, the explanation I found was not complete...So I will add it later when I find more reliable source. If you happen to know the complete explanation, you are more than welcome to tell me and I will add it here :) You are the best!

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

You're exploring a mysterious grid filled with ancient symbols, and you possess a set of unique symbols that you seek within this grid. Your mission is to devise a method to search for these symbols amidst the labyrinth of characters. However, there are rules to follow: You can only find a symbol if it can be formed by connecting adjacent characters along a path within the grid. The path may start at any cell and initially must move either from left to right or from top to bottom.. You're allowed to change direction once during your search, reversing from left to right or from top to bottom. Your task is to calculate the number of times you encounter these symbols within the grid, following these strict guidelines. P.S. For original prompt, pls refer to source image

Constraints

Uknown for now

Example 1

Input:

phrases = ["ac", "cat", "car", "bar", "acdc", "abacaba"]
grid = [["a", "b", "a", "c"], ["x", "a", "c", "d"], ["y", "r", "d", "s"]]

Output:

7

Explanation: Unfortunately, we don't have the access to the video mentioned in the example image

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

解锁全部 29 道题的解法

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

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

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