OAmaster
— / 79已做

There is a board with N cells (numbered 0 to N-1). Each cell holds a token (T) or is empty (E). Each cell with a token contributes points[i]; additionally, every adjacent T-T pair contributes 1 bonus point. Return the total score.

Example

solution([3, 4, 5, 2, 3], "TEETT") = 9
 Token cells 0, 3, 4: 3 + 2 + 3 = 8. Adjacent pair (3,4): +1. Total 9.

solution([3, 2, 1, 2, 2], "ETTTE") = 7
 Token cells 1, 2, 3: 2 + 1 + 2 = 5. Adjacent pairs (1,2), (2,3): +2. Total 7.

solution([2, 2, 2, 2], "TTTT") = 11
 Token cells all: 8. Adjacent pairs (0,1),(1,2),(2,3): +3. Total 11.

Constraints

  • 1 <= N <= 100
  • 1 <= points[i] <= 1000
  • tokens consists of 'E' and 'T' only.

解法

第一遍累加 tokens[i] == 'T' 处的 points[i],第二遍数相邻 T-T 对。复杂度 O(N)

from typing import List

def solution(points: List[int], tokens: str) -> int:
    n = len(points)
    ans = 0
    for i in range(n):
        if tokens[i] == 'T':
            ans += points[i]
    for i in range(n - 1):
        if tokens[i] == 'T' and tokens[i + 1] == 'T':
            ans += 1
    return ans
class Solution {
    public int solution(int[] points, String tokens) {
        int n = points.length;
        int ans = 0;
        for (int i = 0; i < n; i++) {
            if (tokens.charAt(i) == 'T') ans += points[i];
        }
        for (int i = 0; i < n - 1; i++) {
            if (tokens.charAt(i) == 'T' && tokens.charAt(i + 1) == 'T') ans++;
        }
        return ans;
    }
}
#include <string>
#include <vector>

class Solution {
public:
    int solution(std::vector<int>& points, std::string& tokens) {
        int n = (int) points.size();
        int ans = 0;
        for (int i = 0; i < n; i++) {
            if (tokens[i] == 'T') ans += points[i];
        }
        for (int i = 0; i < n - 1; i++) {
            if (tokens[i] == 'T' && tokens[i + 1] == 'T') ans++;
        }
        return ans;
    }
};

There is an array A of N integers. A triplet is a sequence of three consecutive elements whose sum is 0. Each element of A may belong to at most one triplet. Return the largest number of triplets that can be selected simultaneously.

Example

A = [-4, 1, 0, -1, 0, 0, 0, 0, 0]
Pick triplet at indices (1,2,3) = (1, 0, -1). Remaining zeros at indices 4..8.
From those 5 zeros, one triplet of three consecutive zeros (4,5,6). Answer: 2.

A = [-1, 3, -1, 2, -1, 0, -3] -> 1 (only (-1, 2, -1) at indices 2..4)
A = [-1, -2, 3, -1, 0, 1] -> 2

Constraints

  • 1 <= N <= 100
  • -100 <= A[i] <= 100

解法

下标 DP:dp[i] = A[0..i-1] 中三元组最大个数。转移 dp[i] = dp[i-1],若 i >= 3A[i-3]+A[i-2]+A[i-1] == 0,则 dp[i] = max(dp[i], dp[i-3] + 1)。复杂度 O(N)

def solution(A):
    n = len(A)
    dp = [0] * (n + 1)
    for i in range(1, n + 1):
        dp[i] = dp[i - 1]
        if i >= 3 and A[i - 3] + A[i - 2] + A[i - 1] == 0:
            dp[i] = max(dp[i], dp[i - 3] + 1)
    return dp[n]
class Solution {
    public static int solution(int[] A) {
        int n = A.length;
        int[] dp = new int[n + 1];
        for (int i = 1; i <= n; i++) {
            dp[i] = dp[i - 1];
            if (i >= 3 && A[i - 3] + A[i - 2] + A[i - 1] == 0) {
                dp[i] = Math.max(dp[i], dp[i - 3] + 1);
            }
        }
        return dp[n];
    }
}
#include <vector>
#include <algorithm>
using namespace std;

int solution(vector<int>& A) {
 int n = A.size();
 vector<int> dp(n + 1, 0);
 for (int i = 1; i <= n; i++) {
 dp[i] = dp[i - 1];
 if (i >= 3 && A[i - 3] + A[i - 2] + A[i - 1] == 0) {
 dp[i] = max(dp[i], dp[i - 3] + 1);
 }
 }
 return dp[n];
}

A player plays a game where coins are placed on and removed from a table. The game has multiple rounds; at the start of each round the table is empty. Three event types:

  • "i" (increase): one additional coin is placed on the table.
  • "d" (decrease): one coin is taken from the table; if empty, nothing happens.
  • "w" (win): the player wins the round and takes all coins currently on the table; the table resets to empty.

Given the event string for the entire game, return the total number of coins won by the player.

Example

events = "idddiiw" -> 2
 i: 1 coin. d: 0. d,d: still 0. i,i: 2 coins. w: wins 2. Total 2.

events = "iiwdiwi" -> 3
 ii: 2 coins. w: wins 2 (round done). d: empty no-op. i: 1 coin. w: wins 1.
 i: 1 coin (no w follows, lost). Total 3.

Constraints

  • 1 <= |events| <= 200
  • events contains only 'i', 'd', 'w'.

解法

单次扫描,维护计数器:'i' 加 1、'd' 减 1(不低于 0)、'w' 把计数器累入答案后清零。复杂度 O(N)

def solution(events):
    coins = 0
    won = 0
    for c in events:
        if c == 'i':
            coins += 1
        elif c == 'd':
            if coins > 0:
                coins -= 1
        elif c == 'w':
            won += coins
            coins = 0
    return won
class Solution {
    public static int solution(String events) {
        int coins = 0, won = 0;
        for (char c : events.toCharArray()) {
            if (c == 'i') coins++;
            else if (c == 'd') { if (coins > 0) coins--; }
            else if (c == 'w') { won += coins; coins = 0; }
        }
        return won;
    }
}
#include <string>
using namespace std;

int solution(const string& events) {
 int coins = 0, won = 0;
 for (char c : events) {
 if (c == 'i') coins++;
 else if (c == 'd') { if (coins > 0) coins--; }
 else if (c == 'w') { won += coins; coins = 0; }
 }
 return won;
}

A single-player board has N positions described by a string. Each position is empty (.), a player token (T), or a coin (C). The player can have multiple tokens; collecting a coin happens when a token lands on a coin's position (each coin can be collected at most once). In one turn, a token moves exactly three positions to the right (passing over intermediate cells). A token cannot move onto a cell already occupied by another token. Return the maximum number of coins collectible.

Example

board = "TT.TCCCC" -> 3
board = "T...CCCC" -> 1
board = "C..TT.CT.C" -> 2

Constraints

  • 1 <= N <= 100
  • board contains only '.', 'T', 'C'.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

An array contains N two-digit numbers. A group can be chosen iff all members share at least one decimal digit (e.g., 52, 25, 55 all contain 5). Return the maximum number of array elements that can be chosen together.

Example

[52, 25, 11, 52, 34, 55] -> 4 (52, 25, 52, 55 all contain 5)
[71, 23, 57, 15] -> 2 (max digit-coverage is 2)
[11, 33, 55] -> 1
[90, 90, 90] -> 3

Constraints

  • 1 <= N <= 100
  • 10 <= numbers[i] <= 99
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given an undirected tree with N nodes, each assigned a value A[i]. Divide the nodes into the minimum number of groups such that no two nodes in the same group are adjacent. For each group, the cost is max(A[u]) - min(A[u]) over members. Return the sum of costs across all groups.

Since a tree is always bipartite, two groups always suffice. Return the sum of (max − min) over the two color classes.

Constraints

  • 1 ≤ N ≤ 10⁵
  • 1 ≤ A[i] ≤ 10⁹
  • Edges form a valid tree on nodes 1..N.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given an array arr of non-negative integers. Starting from all zeros, in one step you may add 1 to every element of any contiguous subarray. Return the minimum number of steps needed to reach arr.

Example 1

Input:

arr = [2, 1, 0, 2]

Output:

4

Explanation: The transformation can be done in 4 steps:

  • 0000 → 1100: add 1 to the first two positions.
  • 1100 → 2100: add 1 to the first position.
  • 2100 → 2101: add 1 to the fourth position.
  • 2101 → 2102: add 1 to the fourth position again.

Constraints

  • 1 ≤ len(arr) ≤ 10⁵
  • 0 ≤ arr[i] ≤ 10⁹
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

An automatic locker system serves a changing room. For each visit:

  • If the customer has no locker yet, assign the lowest-numbered available locker.
  • If the customer already has a locker, they release it (the locker number becomes available again).

Locker numbers start at 1; all lockers begin empty. Given the visit sequence clients, return the locker number assigned during the last assignment event.

Constraints

  • 1 ≤ N ≤ 10⁵
  • Each clients[i] is a non-empty string.

Example 1

Input:

clients = ["Alice", "Eve", "Bob", "Eve", "Carl", "Alice"]

Output:

2

Explanation:

  • Locker 1 is assigned to Alice;
  • Locker 2 is assigned to Eve;
  • Locker 3 is assigned to Bob;
  • Eve releases locker 2;
  • Locker 2 is assigned to Carl;
  • Alice releases locker 1. The last assigned locker is locker 2, so the function should return 2.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given an array digits of N decimal digits. Choose at most three digits (not necessarily adjacent) and concatenate them in their original order to form an integer. Return the largest integer that can be formed.

Constraints

  • 3 ≤ N ≤ 50
  • 0 ≤ digits[i] ≤ 9

Example 1

Input:

digits = [7, 2, 3, 3, 4, 9]

Output:

749

Explanation: The biggest number that can be built by choosing at most three digits is 749.

Example 2

Input:

digits = [0, 0, 5, 7]

Output:

57

Explanation: The biggest number that can be built by choosing at most three digits is 57.

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

Given an array nums of single-digit integers (0–9) and an integer k, pick a subsequence of length exactly k (preserving order) and concatenate the picked digits into an integer. Return the largest such integer.

Constraints

  • 1 ≤ k ≤ len(nums) ≤ 10⁵
  • 0 ≤ nums[i] ≤ 9

Example 1

Input:

nums = [4, 9, 0, 2]
k = 2

Output:

92

Explanation: N/A for now

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

ISRO is tasked with launching a set of satellites to monitor specific regions on Earth. Each satellite has a limited range within which it can gather data. The goal is to deploy the minimum number of satellites necessary to cover a set of target regions on Earth completely. You are given: An array of target regions, each represented as an interval [start, end], which shows the latitude range of Earth that requires monitoring. A set of satellites, each having a monitoring range [coverageStart, coverageEnd]. Write an algorithm to calculate the minimum number of satellites required to cover all given target regions completely. If coverage is not possible, return -1. Additional Details: Each satellite can cover any region within its range. Overlapping satellite ranges can be used to extend coverage. No partial coverage is allowed—a region must be fully covered by one or more satellites.

Example 1

Input:

targetRegions = [[1, 5], [6, 10], [11, 15]]
satellites = [[1, 6], [5, 9], [10, 15]]

Output:

3

Explanation: The satellite [1, 6] fully covers [1, 5]. The satellite [5, 9] covers [6, 10] (with overlap). The satellite [10, 15] covers [11, 15].

Example 2

Input:

targetRegions = [[1, 4], [5, 8], [9, 12]]
satellites = [[1, 8], [4, 10], [9, 13]]

Output:

2

Explanation: Satellite [1, 8] covers [1, 4] and [5, 8]. Satellite [9, 13] covers [9, 12].

Example 3

Input:

targetRegions = [[1, 5], [6, 10], [11, 15]]
satellites = [[1, 4], [6, 9]]

Output:

-1

Explanation: Satellite [1, 4] cannot fully cover [1, 5]. The target region [11, 15] is not covered.

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

You are given an N×M grid whose cells are either '#' (filled), '_' (empty), or a lowercase letter. Given a string word, determine whether word can be placed left-to-right along some row or top-to-bottom along some column.

A placement is valid when the run of cells used:

  • has length exactly len(word),
  • is bounded by '#' (or the grid edge) on both sides,
  • and at every position the cell is either '_' or already equals the corresponding letter of word.

Return 1 if any valid placement exists, otherwise 0.

Example 1

Input:

grid = [['#', '#', '#', '#'], ['L', '_', '#', ' '], ['A', 'L', 'A', '_'], ['#', 'X', '#', '_']]
word = "ALA"

Output:

0

Explanation: The word ALA does not fit as we have one space left at the end.

L_# ALA_# #X#__ #X#__

Example 2

Input:

grid = [['#', '#', '#', '#'], ['L', '_', '#', ' '], ['A', 'L', 'A', 'N'], ['#', 'X', '#', '_']]
word = "ALAN"

Output:

1

Explanation: The word ALAN fits.

L_# ALAN# #X#__ #X#__

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

A pizza shop offers n pizzas along with m toppings. A customer plans to spend around x coins. The customer should order exactly one pizza, and may order zero, one or two toppings. Each topping may be ordered only once. Given the lists of prices of available pizzas and toppings, what is the price closest to x of possible orders? Here, a price is said to be closer to x when the difference from x is smaller. Note the customer is allowed to make an order that costs more than x. Function Description Complete the function closestCost in the editor. closestCost has the following parameters:

    1. int[] pizzas: an array of integers representing the prices of pizzas
    1. int[] toppings: an array of integers representing the prices of toppings
    1. int x: the budget in coins Returns int: the price closest to x of possible orders

Constraints

  • Customer's budget: 1 ≤ x ≤ 10000
  • Number of pizzas: 1 ≤ n ≤ 10
  • Number of toppings: 0 ≤ m ≤ 10
  • Price of each pizza: 1 ≤ pizzas[i] ≤ 10000
  • Price of each topping: 1 ≤ toppings[i] ≤ 10000
  • The total price of all toppings does not exceed 10000.

Example 1

Input:

pizzas = [800, 850, 900]
toppings = [100, 150]
x = 1000

Output:

1000

Explanation: The customer can spend exactly 1000 coins (two possible orders).

Example 2

Input:

pizzas = [850, 900]
toppings = [200, 250]
x = 1000

Output:

1050

Explanation: The customer may make an order more expensive than 1000 coins.

Example 3

Input:

pizzas = [1100, 900]
toppings = [200]
x = 1000

Output:

900

Explanation: The customer should prefer 900 (lower) over 1100 (higher).

Example 4

Input:

pizzas = [800, 800, 800, 800]
toppings = [100]
x = 1000

Output:

900

Explanation: The customer may not order 2 same toppings to make it 1000.

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

Consider all four-digit codes from 0000 to 9999 (leading zeros allowed). Given an integer S, return how many such codes have a digit sum equal to S. For example, when S = 4 there are 35 codes (e.g. 0022, 1003, 1111, 2020, 4000).

Constraints

  • 0 ≤ S ≤ 36

Example 1

Input:

S = 35

Output:

4

Explanation: The possible codes for S = 35 are: 9998, 9989, 9899, 8999. Therefore, the function should return 4.

Example 2

Input:

S = 4

Output:

35

Explanation:

Example 3

Input:

S = 2

Output:

10

Explanation:

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

You are given n bombs. Each bomb is represented as [x, y, r], where (x, y) is its location and r is its explosion radius. If bomb i is detonated, it directly triggers every bomb j whose Euclidean distance from bomb i is at most r_i. A triggered bomb can then trigger other bombs, creating a chain reaction. You may choose exactly one bomb as the initial detonation. Return the maximum number of bombs that can be detonated.

Constraints

  • 1 ≤ bombs.length ≤ 1000
  • bombs[i].length == 3
  • -10⁵ ≤ x_i, y_i ≤ 10⁵
  • 1 ≤ r_i ≤ 10⁵
  • Use squared distances to avoid floating-point precision issues.

Example 1

Input:

bombs = [[2,1,3],[6,1,4],[4,1,1]]

Output:

3

Explanation: Detonating the first bomb can trigger the third bomb, and the third bomb can trigger the second bomb.

Example 2

Input:

bombs = [[0,0,1],[3,0,1]]

Output:

1

Example 3

Input:

bombs = [[0,0,10],[3,0,1],[6,0,1]]

Output:

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

You are given a string s representing a nested arithmetic expression. The expression uses function-call syntax:

  • add(x, y) evaluates to x + y.
  • sub(x, y) evaluates to x - y. Each argument x or y is either an integer or another nested add/sub expression. The expression is guaranteed to be syntactically valid. Return the integer value of the expression.

Constraints

  • 1 ≤ s.length ≤ 2 * 10⁵
  • Integer literals fit in a 32-bit signed integer.
  • The input expression is valid and contains only add, sub, integer literals, parentheses, commas, and optional spaces.
  • The final result fits in a 32-bit signed integer.

Example 1

Input:

s = "add(1,sub(1,0))"

Output:

2

Explanation: sub(1,0) = 1, then add(1,1) = 2.

Example 2

Input:

s = "add(sub(5,2),sub(1,4))"

Output:

0

Explanation: sub(5,2) = 3 and sub(1,4) = -3, so the result is 0.

Example 3

Input:

s = "sub(add(7,8),sub(3,1))"

Output:

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

Given an n×n matrix, fill it with the integers 1..n² (each used exactly once) so that every row sum, every column sum, and both diagonals all equal the same value (a magic square). If no such filling exists, return null.

Constraints

  • 1 ≤ n ≤ 50
  • A solution exists iff n == 1 or n ≥ 3; for n == 2 return null.

Example 1

Input:

n = 2

Output:

null

Explanation: We need to fill [1, 2, 3, 4] into a 2x2 matrix, which is not possible so return null.

Example 2

Input:

n = 3

Output:

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

Explanation: We need to fill [1, 2, 3... 9] into a 3x3 matrix. This is one way to do it. Each row [8, 3, 4], [1, 5, 9], [6, 7, 2] sum is 15. Each column [8, 1, 6], [3, 5, 7], [4, 9, 2] sum is 15. The two diagonals [8, 5, 2] and [4, 5, 6] sum is 15.

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

You are given 2 arrays representing integer locations of stores and houses (each location in this problem is one-dimensional). For each house, find the store closest to it. Return an integer array result where result[i] should denote the location of the store closest to the i-th house. If many stores are equidistant from a particular house, choose the store with the smallest numerical location. Note that there may be multiple stores and houses at the same location.

Constraints

  • 1 ≤ len(houses), len(stores) ≤ 10⁵
  • 0 ≤ houses[i], stores[i] ≤ 10⁹

Example 1

Input:

houses = [5, 10, 17]
stores = [1, 5, 20, 11, 16]

Output:

[5, 11, 16]

Explanation: The closest store to the house at location 5 is the store at the same location. The closest store to the house at location 10 is the store at the location 11. The closest store to the house at location 17 is the store at the location 16.

Example 2

Input:

houses = [2, 4, 2]
stores = [5, 1, 2, 3]

Output:

[2, 3, 2]

Explanation: No explanation

Example 3

Input:

houses = [4, 8, 1, 1]
stores = [5, 3, 1, 2, 6]

Output:

[3, 6, 1, 1]

Explanation: No explanation

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

The organizers of a gaming tournament want to analyze player participation based on event logs. There are n event logs, where arr[i] indicates the playerId of the player who participated in the ith event. The organizers need to identify subarrays of these logs that are consistent, meaning that the frequency of the most frequent player in the subarray matches the frequency of the least frequent player in the entire array. Determine the maximum length of such consistent logs. Function Description Complete the function findConsistentLogs with the following parameters: int arr[n]: the playerIds present in the event logs Returns int: the maximum length of the consistent logs

Constraints

1 ≤ n ≤ 10⁴

Example 1

Input:

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

Output:

8

Explanation: Given:

  • n = 10
  • arr = [1, 2, 1, 3, 4, 2, 4, 3, 3, 4] The frequencies of playerIds 1 and 2 are 2. The frequencies of playerIds 3 and 4 are 3. The minimum frequency in the array is 2. The longest valid subarray with this property is [1, 2, 1, 3, 4, 2, 4, 3], which has 8 elements. In this subarray, the most common element appears 2 times, which matches the minimum frequency in the entire array. Therefore, the maximum length of consistent logs is 8.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given an array nums of n positive integers, find a contiguous subarray (length ≥ 2) that maximizes min(subarray) + max(subarray). Return that maximum value. Solve better than O(n³).

Constraints

  • 2 ≤ n ≤ 10⁵
  • 1 ≤ nums[i] ≤ 10⁹

Example 1

Input:

nums = [4, 6, 2, 8, 10]

Output:

18

Explanation: The contiguous subarray with the largest min + max is [8, 10], where the min is 8 and the max is 10. Therefore, the answer is 10 + 8 = 18.

Example 2

Input:

nums = [6, 2, 9, 1, 7]

Output:

11

Explanation: The contiguous subarray with the largest min + max is [2, 9], where the min is 2 and the max is 9. Therefore, the answer is 2 + 9 = 11.

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

Given an array nums of single-digit integers, choose exactly three of them in their original order and concatenate them to form a 3-digit number. Return the largest such number.

Constraints

  • 3 ≤ len(nums) ≤ 50
  • 0 ≤ nums[i] ≤ 9
  • The first chosen digit must be non-zero (so the result has three digits).

Example 1

Input:

nums = [7, 4, 3, 8, 2]

Output:

782

Explanation:

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

You are given an alphanumeric string S and an integer K. Form a new string T = S repeated K times (so T = S concatenated K times). Then repeat the following alternating operations on T until a single character remains:

  1. Remove every alternate character starting from the first character (i.e. drop positions 0, 2, 4 …).
  2. Remove every alternate character starting from the last character (i.e. drop the last position, then every other moving left).

Return the last remaining character as a string.

Constraints

  • 1 ≤ |S| ≤ 100
  • 1 ≤ K ≤ 10⁴
  • S contains letters, digits, or any of $ # & *.

Example 1

Input:

S = "abcd"
K = 3

Output:

"b"

Explanation: The following operations can be performed on the string "abcd":

  • S = a b c d a b c d a b c d (The string obtained after appending the given string K-1 times)
  • S = b d b d b d (The string obtained after removing every alternate character from the beginning)
  • S = b b b (The string obtained after removing every alternate character from the end)
  • S = b Since, b is the only character left after performing all the operations. Therefore, b is returned as the output.

Example 2

Input:

S = "j#k&h"
K = 5

Output:

"&"

Explanation: The following operations can be performed on the string "j#k&h":

  • S = j # k & h j # k & h j # k & h j # k & h j # k & h (The string obtained after appending the given string K-1 times)
  • S = # & j k h # & j k h # & (The string obtained after removing every alternate character from the beginning)
  • S = # j h & k # (The string obtained after removing every alternate character from the end)
  • S = j & # (The string obtained after removing every alternate character from the beginning)
  • S = & & is the only character left after performing all the operations. Therefore, & is returned as the output.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

A health monitor records two parallel arrays: heartRate[i] is the heart rate at sample i, and activityLevel[i] is the activity level (e.g. "Low", "Normal", "High") at that sample. For each activity level, compute the maximum heart-rate difference (max − min) across all samples sharing that level. Return the largest such per-level difference.

Constraints

  • 1 ≤ len(heartRate) == len(activityLevel) ≤ 10⁵
  • 0 ≤ heartRate[i] ≤ 300

Example 1

Input:

heartRate = [100, 87, 90, 90, 125]
activityLevel = ["Normal", "Normal", "Normal", "High", "Low"]

Output:

13

Explanation: Within the three periods of "Normal" activity level, the heart rate ranges from 87 to 100, with the maximum difference being 13.

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

Given a list of integers nums, find the length of the longest subsequence (preserving original order) such that each chosen element is exactly 1 greater than the previously chosen one. Return that length.

Constraints

  • 1 ≤ len(nums) ≤ 10⁵
  • -10⁹ ≤ nums[i] ≤ 10⁹

Example 1

Input:

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

Output:

5

Explanation: The longest subsequence with consecutive elements increasing by 1 is 1, 2, 3, 4, 5, which has a length of 5.

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

Given an integer array nums, return the maximum frequency of any single value (i.e. how many times the most common element appears).

Constraints

  • 1 ≤ len(nums) ≤ 10⁵
  • -10⁹ ≤ nums[i] ≤ 10⁹

Example 1

Input:

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

Output:

4

Explanation: In the given array, the number 3 appears the maximum number of times, which is 4 times.

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

Given an integer array nums, you may change the value of at most one element to any integer of your choice. Return the maximum possible length of a contiguous non-decreasing subarray after that change.

Constraints

  • 1 ≤ len(nums) ≤ 10⁵
  • -10⁹ ≤ nums[i] ≤ 10⁹

Example 1

Input:

nums = [2, 4, 6, 8, 0, 9]

Output:

6

Explanation: By changing the value at index 4 from 0 to 8, the array becomes [2, 4, 6, 8, 8, 9], which is non-decreasing. The length of this subarray is 6, which is the longest possible non-decreasing subarray after making one change.

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

Given an integer array arr, return the length of the longest contiguous non-decreasing subarray (a window where every element is its left neighbor).

Constraints

  • 1 ≤ len(arr) ≤ 10⁵
  • -10⁹ ≤ arr[i] ≤ 10⁹

Example 1

Input:

arr = [0, 7, 3, 10, 2, 4, 6, 8, 0, 9, -20, 4]

Output:

4

Explanation: The maximum length of non-decreasing subarray is 4, which corresponds to the subarray [2, 4, 6, 8].

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

You are given a tree-shaped undirected graph consisting of n nodes labeled 1...n and n-1 edges. The i-th edge connects nodes edges[i][0] and edges[i][1] together. For a node x in the tree, let d(x) be the distance (the number of edges) from x to its farthest node. Find the min value of d(x) for the given tree. The tree has the following properties:

  • It is connected.
  • It has no cycles.
  • For any pair of distinct nodes x and y in the tree, there's exactly 1 path connecting x and y. Function Description Complete the function findMinDistanceToFurthestNode in the editor. findMinDistanceToFurthestNode has the following parameters:
  • int n: the number of nodes
  • int edges[n-1][2]: an array of n-1 edges where each edges[i] contains two integers representing an edge connecting the nodes Returns int: the minimum distance to the furthest node

Constraints

  • 1 ≤ n ≤ 10⁵
  • edges.length == n - 1
  • The edges form a valid tree on nodes 1..n.

Example 1

Input:

n = 6
edges = [[1, 4], [2, 3], [3, 4], [4, 5], [5, 6]]

Output:

2

Explanation: No explanation available.

Example 2

Input:

n = 6
edges = [[1, 3], [4, 5], [5, 6], [3, 2], [3, 4]]

Output:

2

Explanation: No explanation available.

Example 3

Input:

n = 2
edges = [[1, 2]]

Output:

1

Explanation: No explanation available.

Example 4

Input:

n = 10
edges = [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9], [9, 10]]

Output:

5

Explanation: No explanation available.

Example 5

Input:

n = 10
edges = [[7, 8], [7, 9], [4, 5], [1, 3], [3, 4], [6, 7], [4, 6], [2, 3], [9, 10]]

Output:

3

Explanation: No explanation available.

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

You are given a tree consisting of n vertices. You can perform the following operation at most k times: delete a single leaf of the tree (the operation can produce new leaves, that can be deleted later). The resulting tree must have as small diameter as possible. Find the minimum possible diameter. Input Format The first line contains two space separated integers n and k. Each of the next n-1 lines contains two space separated integers, describing the current tree edge. It's guaranteed that the given graph is a tree. Constraints 0 < n ≤ 1e5 0 < k < n

Example 1

Input:

n = 4
k = 0
edges = [[1, 2], [2, 3], [4, 3]]

Output:

3

Explanation: :3

Example 2

Input:

n = 4
k = 1
edges = [[2, 3], [4, 3], [1, 4]]

Output:

2

Explanation: :o

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

Given that a microwave takes key stroke inputs and a target cooking time, find the optimal input considering the following costs for input: Input 999 will be interpreted as 9 minutes 99 seconds. Input 81 as 81 seconds. Input 1221 as 12 minutes 21 seconds. The cost of each key stroke is 1, and the cost of moving the finger to a different key is 2. For example, input 999 has a cost of 3, input 1122 has a cost of 6, and input 1234 has a cost of 10. The input has to be within 10% of the target time. If the cost is the same, select the input that's closest to the target time. For example, for a target time of 10 minutes, 888 is the optimal input (not 999). Function Description Complete the function findOptimalInput in the editor. findOptimalInput has the following parameter:

  • targetTime: the target cooking time in seconds Returns int: the optimal input value
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given a rooted tree T with N nodes (root = node 1), each labeled with a character C[i]. For each node u, build a string S(u) recursively: visit children of u in increasing node-number order, append each child's S(v), and finally append C[u]. For each of Q queries on a node u, return 1 if S(u) is a palindrome, otherwise 0.

Constraints

  • 1 ≤ N, Q ≤ 2·10⁵
  • Each C[i] is a single lowercase letter.

Example 1

Input:

n = 5
edges = [[1, 2], [1, 3], [2, 4], [2, 5]]
c = ['a', 'b', 'a', 'b', 'c']
queries = [1, 2]

Output:

[0, 1]

Explanation: For node 1, S = "bcbaa" For node 2, S = "bcb"

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

You are given a pattern string and a list of candidate strings. The pattern is plain text plus optional character classes of the form [abc...], where any one of the listed characters matches one position. Return all strings that fully match the pattern.

Constraints

  • 1 ≤ len(pattern) ≤ 100
  • 1 ≤ len(strings) ≤ 1000, each string up to length 100.

Example 1

Input:

pattern = "tele[op]ho[bnm]e"
strings = ["cat", "dog", "telephone", "telephonepole", "tele", "telehoe", "teleophobme"]

Output:

["telephone"]

Explanation: :O

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

Given a binary tree with n nodes and an array edges where each element is of the form [from, to], representing an edge from from to to. Remove all the edges in the edges array from the tree and return an array with the total node count in each connected component formed after removing all the edges from the tree. Note: All the node values in the Binary Tree are unique.

Example 1

Input:

Nodes = ["1", "2", "3", "4", "5", "null", "null"]
Edges = [[1, 2], [2, 4]]

Output:

[2,2,1]

Explanation: The output shows that there are 3 components formed after removing the edges from the binary tree, and number of nodes in those components are 2, 2 and 1 respectively.

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

You have a list of meetings in your calendar with a start and end time. You are very busy, so meetings can overlap. You also have one "Do Not Schedule" (DNS) interval during which you don't attend any meeting. Any meeting schedule that overlaps with a DNS slot is automatically cut such that it does not overlap with the DNS slot anymore. Return a list of non-overlapping time intervals when you are in a meeting. Function Description Complete the function getMeetingIntervals in the editor. getMeetingIntervals has the following parameters:

    1. int[][] meetings: an arr of intervals representing meeting times
    1. Interval dns: an interval representing the "Do Not Schedule" time Returns int[][]: an arr of non-overlapping intervals when you are in a meeting

Example 1

Input:

meetings = [[1, 7], [5, 10], [12, 30], [22, 30], [40, 50], [60, 70]]
dns = [18, 25]

Output:

[[1, 10], [12, 18], [25, 30], [40, 50], [60, 70]]

Explanation:

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

Implement a class ImageStream with constructor (allImages, markedFavorites) and a method getNext() that returns images in the following order: first every image in markedFavorites (in given order), then every image in allImages that is not in markedFavorites (preserving the original order from allImages). Once exhausted, getNext() returns null / empty.

Assume markedFavorites is a subset of allImages and both stay unchanged after construction. Setup work in the constructor should be lightweight.

Follow-up: What changes if markedFavorites already appears in the same relative order as in allImages?

Example 1

Input:

allImages = ["i1", "i2", "i3", "i4", "i5", "i6", "i7", "i8", "i9", "i10"]
markedFavorites = ["i2", "i5", "i7"]

Output:

"i2, i5, i7, i1, i3, i4, i6, i8, i9, i10"

Explanation: :)

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

In a neighborhood, there are N empty houses numbered from 1 to N arranged in a line. Each day, starting from day 1, one house will be occupied by residents. The sequence of occupied houses is given as a permutation of length N. On the ith day, the house with the number given by the ith element of the permutation will be occupied. The neighborhood will be considered happy if there is at least one set of consecutive occupied houses. On which day will the neighborhood become happy? Note: A permutation of length N is an array of N integers where each element is between 1 and N, with no repetitions. Function Description Complete the function solve. This function takes the following 3 parameters and returns the required answer: N: Represents the number of houses M: Represents the number of consecutive houses needed house: Represents an array indicating the house that will be filled on each day Input format for custom testing Note: Use this input format if you are testing against custom input or writing code in a language where we don't provide boilerplate code. The first line contains N denoting the number of houses. The second line contains M denoting the number of consecutive houses needed. The third line contains an array house denoting the house that will be filled on each day. Output format Print a single integer representing the first day on which the neighborhood becomes happy.

Example 1

Input:

N = 3
M = 1
house = [3, 2, 1]

Output:

1

Explanation: tomtom's note: Not entirely sure about the explanation O.o Since the requirement is for at least one set of consecutive occupied houses and the first house to be occupied is house number 3, the neighborhood becomes happy on day 1.

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

Write a function to check if the given input string is balanced or not. The input string will contain parentheses and digits. whenever digit is occurred you need to remove digit number left side paranathesis in any order (ex: if digit is 2 you need to remove 2 paranthesis from left side means if inp == )(1, either I can remove ( or ) left side of 1). string is balanced if opening paranthesis is equal to closing (ex: (()), ()(), ()), treat each digit seperately if 11 is present in input treat them as 2 ones. pps: 1 == true, 0 == false

Example 1

Input:

s = "(()1(1)) "

Output:

1

Explanation: :}

Example 2

Input:

s = ")1()"

Output:

1

Explanation: o.o

Example 3

Input:

s = ")(1))"

Output:

0

Explanation: :3

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

Given two strings A</co

Constraints

Unknwon for now

Example 1

Input:

A = "abc"
B = "abcab"

Output:

"cab"

Explanation: String B is a superstring of string A because it contains all the characters of A in various sequences. Among these sequences, ("cab", "abc", "bca") meet the conditions, and the largest lexicographically ordered substring among them is "cab".

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

You are given a text string and a dictionary of token-to-id mappings. Starting from the beginning of text, repeatedly choose the longest dictionary token that matches the current position and output its id. If no dictionary token matches, output the current character itself and advance by one character. Return the sequence of emitted ids and literal characters.

Constraints

If multiple dictionary entries have the same token, use the first mapping provided. The tokenization is greedy and scans left to right.

Example 1

Input:

text = "applepie"
dictionary = [["app","B"],["apple","A"],["pie","P"]]

Output:

["A","P"]

Explanation: apple is preferred over app because it is the longest match at index 0.

Example 2

Input:

text = "xabcd"
dictionary = [["ab","1"],["abc","2"],["bc","3"]]

Output:

["x","2","d"]

Explanation: The first character has no match, then abc is the longest token starting at index 1.

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

Given an array of integers, you can perform 2 operations on them. Operation 1: You can make a[i] = a[i-1] - 1 (i ≥ 0 and i Operation 2: You can make a[i] = 0. Input: Array A, int X, int Y. Output: You have to print the max subarray filled with zeros that can be made by performing Operation 1 at the most X times and Operation 2 at the most Y times.

Constraints

N/A

Example 1

Input:

A = [4, 3, 0, 1]
X = 2
Y = 1

Output:

3

Explanation: Step 1: [4, 0, 0, 1] X=2, Y=0 Step 2: [4, 0, 0, 0] X=1, Y=0 Therefore, the output is 3.

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

Given a

Example 1

Input:

points = [25, 1, 3, 99, 4]

Output:

100

Explanation: Take 1 and 99, the solution is 100.

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

You are provided with an array powerValues of integers and an integer k. Select exactly k elements from the array such that their sum is maximized. Return that maximum sum.

Constraints

  • 1 ≤ k ≤ powerValues.length ≤ 10⁵
  • 1 ≤ powerValues[i] ≤ 10⁹

Example 1

Input:

powerValues = [1, 2, 3, 10, 9]
k = 2

Output:

13

Explanation: No explanation is provided for now

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

You are given an array A consisting of N numbers. In one move you can delete either the first two, the last two, or the first and last elements of A. No move can be performed if the length of A is smaller than 2. The result of each move is the sum of the deleted elements. Write a function: class Solution { public int solution(int[] A); } that, given an array A of N integers, returns the maximum number of moves that can be performed on A, such that all performed moves have the same result.

Constraints

N/A

Example 1

Input:

A = [3, 1, 5, 3, 3, 4, 2]

Output:

3

Explanation: The first move should delete two last elements (4 and 2 with sum = 6), then A = [3, 1, 5, 3, 3]. The second move may delete first and last elements (3 and 3 with sum = 6), then A = [1, 5, 3]. The third move should delete first two elements (1 and 5 with sum = 6), then A = [3].

Example 2

Input:

A = [4, 1, 4, 3, 3, 2, 5, 2]

Output:

4

Explanation: It is possible to delete the first and last elements four times, as each such pair of elements sums up to 6.

Example 3

Input:

A = [1, 9, 1, 1, 1, 1,1,1, 8, 1]

Output:

1

Explanation: There is no way to perform move that results with the same sum more than once.

Example 4

Input:

A = [1, 9, 8, 9, 5, 1, 2]

Output:

3

Explanation: The first move should delete the first two elements, then the second and third moves should delete first and last elements twice.

Example 5

Input:

A = [1, 1, 2, 3, 1, 2, 2, 1, 1, 2]

Output:

4

Explanation: The function should return 4.

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

You are given a string that represents time in the format hh:mm. Some of the digits are blank (represented by ?). Fill in ? such that the time represented by this string is the maximum possible. Maximum time: 23:59, minimum time: 00:00. You can assume that input string is always valid.

Constraints

Unknown yet. If u happen to know about it feel free to lmk. tysm! ~^~

Example 1

Input:

time = "?4:5?"

Output:

"14:59"

Explanation: Provided by Groot for reference (May not be 100% accurate ) - Replace the first '?' with '1' to make the hour as large as possible, which is '14'. The last '?' is replaced with '9' to make the minutes as large as possible, resulting in "14:59".

Example 2

Input:

time = "23:5?"

Output:

"23:59"

Explanation: Provided by Groot for reference (May not be 100% accurate ) - The hour is already at its maximum, '23'. Replace the last '?' with '9' to make the minutes as large as possible, resulting in "23:59".

Example 3

Input:

time = "?2:22"

Output:

"23:22"

Explanation: Provided by Groot for reference (May not be 100% accurate ) - Replace the first '?' with '2' to make the hour as large as possible, which is '23'. The minutes are already given, so the final time is "23:22".

Example 4

Input:

time = "0?:??"

Output:

"09:59"

Explanation: Provided by Groot for reference (May not be 100% accurate ) - Replace the second '?' with '9' to make the hour as large as possible, which is '09'. Replace the last two '?'s with '59' to make the minutes as large as possible, resulting in "09:59".

Example 5

Input:

time = "??:??"

Output:

"23:59"

Explanation: Provided by Groot for reference (May not be 100% accurate ) - Replace the first '?' with '2' and the second '?' with '3' to make the hour as large as possible, which is '23'. Replace the last two '?'s with '59' to make the minutes as large as possible, resulting in "23:59".

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

There are n guests who are invited to a party. The k-th guest will attend the party at time S[k] and leave the party at time E[k]. Given an integer array S and an integer array E, both of length n, return an integer denoting the minimum number of chairs you need such that everyone attending the party can sit down. Function Description Complete the function minChairs in the editor. minChairs has the following parameters:

  • int S[n]: an array of integers representing the arrival times
  • int E[n]: an array of integers representing the leaving times Returns int: the minimum number of chairs needed

Constraints

Unknown yet. If you happen to know about it, feel free to lmk! TYSM ~3~

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

This is like merge interval question but t

Example 1

Input:

intervals = [["Foo", "10", "30"], ["Bar", "15", "45"]]

Output:

["10 15 Foo", "15 30 Foo, Bar", "30 45 Bar"]

Explanation:

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

There is an array A consisting of N integers. Choose at most one element to multiply by -1 in order to obtain an array whose sum of elements is as close to 0 as possible. That is, find the sum with the minimum absolute value. that, given an array A, returns the minimum absolute value of the sum of A that can be obtained.

Constraints

  • N is an integer within the range [1..100,000];
  • each element of array A is an integer within the range [-1,000..1,000].

Example 1

Input:

A = [1, 3, 2, 5]

Output:

1

Explanation: For A = [1, 3, 2, 5], after multiplying the last element by -1, A will be equal to [1, 3, 2, -5]. Its sum is 1. It is not possible to obtain any sum closer to 0. The function should return 1.

Example 2

Input:

A = [-4, 0, -3, 3]

Output:

2

Explanation: For A = [-4, 0, -3, 3], we can multiply -4 by -1 and therefore obtain A = [4, 0, -3, 3]. Its sum is 2. The function should return 2.

Example 3

Input:

A = [4, -3, 5, -7]

Output:

1

Explanation: Assume that A = [4, -3, 5, -7]. Its sum is -1. There is no possible move that could improve this result. The function should return 1.

Example 4

Input:

A = [-15, 18, 1, -1, 10, -22]

Output:

9

Explanation: It is optimal to change -1 to 1. The function should return 9.

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

Given an Array A, find the minimum amplitude you can get after cha

Constraints

We dont know it yet. If you happen to know about it feel free to let us know tysm! ^3^

Example 1

Input:

A = [-1, 3, -1, 8, 5, 4]

Output:

2

Explanation: We can change -1, -1, 8 to 3, 4 or 5.

Example 2

Input:

A = [10, 10, 3, 4, 10]

Output:

0

Explanation: Change 3 and 4 to 10.

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

Given an array of roses. roses[i] means

Constraints

Unknown yet. If you happen to know about it, feel free to lmk! TYSM ~3~

Example 1

Input:

roses = [1, 2, 4, 9, 3, 4, 1]
k = 2
n = 2

Output:

4

Explanation: day 1: [b, n, n, n, n, n, b] The first and the last rose bloom. day 2: [b, b, n, n, n, n, b] The second rose blooms. Here the first two bloom roses make a bouquet. day 3: [b, b, n, n, b, n, b] day 4: [b, b, b, n, b, b, b] Here the last three bloom roses make a bouquet, meeting the required n = 2 bouquets of bloom roses. So return day 4.

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

You're working on a data storage sy

Example 1

Input:

grid = [[1, 0, 1], [0, 1, 0], [1, 0, 0]]

Output:

4

Explanation: :)

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

There are some processes that need to be executed. Amount of a load that process causes on a server that runs it, is being represented by a single integer. Total load caused on a server is the sum of the loads of all the processes that run on that server. You have at your disposal two servers, on which mentioned processes can be run. Your goal is to distribute given processes between those two servers in the way that, absolute difference of their loads will be minimized. Given an array of n integers, of which represents loads caused by successive processes, return the minimum absolute difference of server loads. Function Description Complete the function minAbsDifference in the editor. minAbsDifference has the following parameter:

  • int[] loads: an array of integers representing the loads Returns int: the minimum absolute difference of server loads

Constraints

Unknown yet. If you happen to know about it, feel free to lmk! TYSM ~3~

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

You are given two integer arrays: int[] multiples: the multipliers available in the shop int[] prices: the corresponding prices for each multiplier Both arrays have the same length n, and the i-th multiplier (multiples[i]) costs prices[i] coins to purchase. You start with: 0 coins A base gain rate of 1 coin per second When you purchase a multiplier, your coin gain rate is multiplied by that value. For example: Start: gain = 1x Buy 3x -> gain becomes 3x Buy 4x -> gain becomes 3 × 4 = 12x You can only make purchases when you have enough coins to afford the multiplier. Your goal is to purchase all the multipliers, in some order, such that the total time taken to finish all purchases is minimized. Function Description Complete the function minimizeTotalTime in the editor. minimizeTotalTime has the following parameters:

  • int[] multiples: an array of multipliers available in the shop
  • int[] prices: an array of corresponding prices for each multiplier Returns int[]: an array of indices representing the order in which to purchase the multipliers to minimize the total time

Constraints

:O

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

You are given rental requests, where each request is represented as [pickupTime, returnTime]. A single car cannot serve overlapping requests. If one request ends exactly when another begins, the same car may serve both. Return one deterministic minimum-car assignment using the following canonical rules:

  • Process requests in ascending order of pickupTime, breaking ties by returnTime.
  • When multiple cars are available, reuse the available car with the smallest car id.
  • When no existing car is available, create a new car with the next unused id starting from 0. Each returned string must use the format "carId: (p1,r1) (p2,r2) ...". The number of returned lines is the minimum number of cars needed. Function Description Complete the function assignMinimumCars in the editor below. assignMinimumCars has the following parameter:
  • int[][] requests: rental intervals [pickupTime, returnTime] Returns String[]: the deterministic assignment lines in ascending car id order.

Constraints

  • 1 ≤ requests.length ≤ 2 * 10⁵
  • 0 ≤ pickupTime < returnTime ≤ 10⁹
  • The returned assignment must follow the deterministic rules stated above.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given a binary string s. In one operation, you can flip a subarray of length exactly k (flip all bits in that subarray). Return the minimum number of such operations needed to make the string alternating (i.e., no two adjacent bits are the same). If it's not possible, return -1.

Example 1

Input:

s = "00010111"
k = 3

Output:

2

Explanation: ^~^

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

You're optimizing video chunks for streaming. Each chunk has a size represented in a 0-indexed array nums. To ensure smooth playback, chunk sizes must be in non-decreasing order. You can split any chunk into two smaller chunks whose sizes add up to the original. For example, if nums = [10,5,8], you can split 10 into [4,6] making it [4,6,5,8]. Return the minimum number of split operations needed to make the array sorted in non-decreasing order. The candidate was able to come up with an O(n²) solution within 15 minutes but was asked to improve it to O(n), which they couldn't achieve.

Example 1

Input:

nums = [10, 5, 8]

Output:

1

Explanation: :) The output may be 1. If anything is found to be wrong, I am more than happy to make modifications.

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

(no statement available)

Constraints

0 ≤ N ≤ 2 * 10⁹

Example 1

Input:

N = 6

Output:

1

Explanation: You need to decrease N by 1 to make it 5 as binary representation of 5 is Palindromic (101) or you can increase N by 1 to make it 7 as its binary is also palindromic (111).

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

Relative sorting is defined as sorting two arrays (both in strictly ascending order) such that the only operation allowed is swapping i'th element of one array with the i'th element of the other array. An array is said to be in strictly ascending order if i'th element of the array is smaller than (i+1)'th element of the array. You are given two arrays of size N. print the minimum number of swaps required to make both arrays relatively sorted. Note:

  • If the arrays are already relatively sorted, then print '0'
  • If the arrays cannot be relatively sorted, then print '-1'. Input Format: The input consist of 3 lines:
  • First line consist of the size of each array, i.e. N
  • The next two lines contain N elements each separated by a space Output Format: The output will be an integer i.e., the minimum number of swaps required to make both arrays relatively sorted.

Constraints

0 0 < Elements in array ≤ 10⁹`

Example 1

Input:

N = 4
A = [1, 4, 4, 9]
B = [2, 3, 5, 10]

Output:

1

Explanation: To make both arrays strictly increasing we can swap 4 and 3 or 4 and 5.

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

Given a hotel which has 10 floors [0-9] and each floor has 26 rooms [A-Z]. You are given a sequence of rooms, where + suggests room is booked, - room is freed. You have to find which room is booked maximum number of times. You may assume that the list describes a correct sequence of bookings in chronological order; that is, only free rooms can be booked and only booked rooms can be freed. All rooms are initially free. Note that this does not mean that all rooms have to be free at the end. In case, 2 rooms have been booked the same number of times, return the lexicographically smaller room. Function Description Complete the function mostBookedHotelRoom in the editor. mostBookedHotelRoom has the following parameter:

  • String[] A: an array of strings representing the sequence of room bookings and releases Returns String: the room that is booked the maximum number of times

Constraints

  • N (length of input) is an integer within the range [1, 600]
  • Each element of array A is a string consisting of three characters: "+" or "-", a digit "0"-"9"; and uppercase English letter "A" - "Z"
  • The sequence is correct. That is every booked room was previously free and every freed room was previously booked.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

An engineer is tasked with developing an integrated binary circuit that processes an input binary string ( s ). This binary string, which consists solely of 0s and 1s, needs to be rearranged so that all 1s are moved to the end of the string. For example, the string "01010" should be transformed into "00011". To achieve this, the engineer can perform a series of operations where any "1" from the string can be moved to the right. The operation cost is defined as ( 1 + ) the number of positions the "1" is moved. For instance, in the string "100010", moving the first "1" three positions to the right costs ( 1 + 3 = 4 ). Each "1" must be moved as far to the right as possible during the operation. Given a binary string ( s ), determine the maximum total cost of operations required to segregate the string so that all 1s are at the end.

Example 1

Input:

s = "110100"

Output:

13

Explanation: The target string should be "000111". To maximize the number of operations, the process would be:

  • Move the second character to the third position at a cost of 2. The string becomes "101100".
  • Move the first character to the second position at a cost of 2. The string becomes "011100".
  • Move each "1" two positions to the right, each at a cost of 3. The total cost is ( 2 + 2 + 3*3 = 13 ). Therefore, the maximum number of operations required to segregate the string is 13.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given an array A of length N, a starting index cur, and a distance D. Your task is to iteratively update the array A starting from index cur. At each step, replace A[cur] with A[cur] + 1, then find the nearest index (left or right, within distance D) where this new value exists in the array. If multiple indices exist at the same distance, choose the leftmost index. If no such index exists within distance D, keep the value in the same index and stop updating. Function Description Complete the function nearestValueReplacement in the editor. nearestValueReplacement has the following parameters:

    1. int[] A: an array of integers
    1. int cur: the starting index
    1. int D: the distance within which to search Returns int[]: the updated array

Example 1

Input:

A = [1, 3, 2, 3, 4, 5, 2]
cur = 2
D = 2

Output:

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

Explanation: ;o

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

In an ocean, there are islands marked by 1. Water is represented by 0. Determine how many unique shapes (no rotation or mirror) among these islands. Islands are connected 4-directionally. Function Description Complete the function numDistinctIslands in the editor. numDistinctIslands has the following parameter:

  • int[][] grid: a 2D array of integers representing the ocean Returns int: the number of unique island shapes

Example 1

Input:

grid = [[1, 1, 1, 1, 0, 0], [1, 1, 0, 0, 0, 1], [0, 0, 1, 1, 0, 1], [1, 1, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1], [1, 0, 1, 1, 0, 0]]

Output:

4

Explanation: There are 4 unique island shapes:

  • the 2 6-sized islands,
  • the 2 2-sized islands,
  • the 1 2-sized island,
  • the 1 1-sized island. Standard BFS/DFS problem with a translation of the starting point to the origin of each island. The solution is done correctly and optimally with O(n) complexity.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given a string S, we can split S into 2 strings: S1 and S2. Return the number of ways S can be split such that the number of unique characters between S1 and S2 are the same.

Constraints

We dont know yet. If you happen to know aout it feel free to lmk. TYSM!

Example 1

Input:

s = "aaaa"

Output:

3

Explanation: We can get a - aaa, aa - aa, aaa - a.

Example 2

Input:

s = "bac"

Output:

0

Explanation: There are no ways to split the string such that the number of unique characters between S1 and S2 are the same.

Example 3

Input:

s = "ababa"

Output:

2

Explanation: We can get ab - aba, aba - ba.

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

A log file contains a series of entries represented by a permutation of length n integers. To analyze the log efficiently, n operations, indexed from 0 to n-1, are available. Each operation involves swapping two entries in the log. The goal is to select some of these n operations and apply them in any order to the log entries to produce the lexicographically smallest permutation, facilitating a more streamlined log analysis. The task is to return this lexicographically smallest permutation of entries. Additional notes: Each operation can be used at most once. 0-based indexing is considered. A permutation is an array consisting of distinct integers from 1 to n in arbitrary order. The permutation p of length n is lexicographically less than the permutation q of length n if there is an index i such that for all j from 0 to i-2, the condition p[j] = q[j] is satisfied, and p[i] < q[i].

Constraints

  • 1 < n ≤ 2 * 10⁵
  • 1 ≤ entries[i] < n
  • It is guaranteed that the array entries is a permutation of length n.

Example 1

Input:

entries = [5, 4, 1, 3, 2]

Output:

[1, 5, 2, 4, 3]

Explanation: Apply operation 2 to swap entries[1] and entries[2] to get entries [5, 1, 4, 3, 2]. Apply operation 1 to swap entries[0] and entries[1] to get entries [1, 5, 4, 3, 2]. Apply operation 4 to swap entries[3] and entries[4] to get entries [1, 5, 4, 2, 3]. Apply operation 3 to swap entries[2] and entries[3] to get entries [1, 5, 2, 4, 3]. Hence, the answer is [1, 5, 2, 4, 3].

Example 2

Input:

entries = [4, 3, 2, 1]

Output:

[1, 4, 3, 2]

Explanation: Apply operation 3 to swap entries[2] and entries[3] to get entries = [4, 3, 1, 2]. Apply operation 2 to swap entries[1] and entries[2] to get entries= [4, 1, 3, 2]. Apply operation 1 to swap entries[0] and entries[1] to get entries = [1, 4, 3, 2].

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

The distance between 2 binary strings is the sum of their lengths

Constraints

Unknown yet. If you happen to know about it, feel free to lmk! TYSM ~3~

Example 1

Input:

binaryStrings = ["1011000", "1011110"]

Output:

6

Explanation: The common prefix for these two numbers is 1011, so the distance is len("000") + len("110") = 3 + 3 = 6.

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

Write a function: int solution(vector &points, string &tokens); that, given an array of integers points and a string tokens, both of length N, returns the total number of points in the game. Assume that:

  • array points and string tokens are of the same length N;
  • N is an integer within [1, 100];
  • each element of array points is an integer within the range [1, 1,000];
  • string tokens consists only of the characters 'E' and/or 'T'. Big props to Aura Man!

Example 1

Input:

points = [4, 0, 2, 2]
tokens = "TEET"

Output:

9

Explanation: Cells 0, 3 and 4 contain tokens. The value of points in these cells is 8. Also, there is one pair of adjacent cells with tokens, which gives 1 extra point. The function should return 9.

Example 2

Input:

points = [3, 2, 1, 2, 2]
tokens = "TTTE"

Output:

10

Explanation: Cells 0, 1 and 2 contain tokens. The value of points in these cells is 8. Also, there are two pairs of adjacent cells with tokens, which results in 2 extra points. The function should return 10.

Example 3

Input:

points = [2, 2, 2, 2]
tokens = "TTTT"

Output:

11

Explanation: All cells contain tokens. The function should return 11.

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

A 2-D grid consisting of some blocked (represented as '#') and some unblocked (represented as '.') cells is given. The starting position of a pointer is in the top-left corner of the grid. It is guaranteed that the starting position is in an unblocked cell, and it is also guaranteed that the bottom-right cell is unblocked. Each cell of the grid is connected with its right, left, top, and bottom cells (if those cells exist). It takes 1 second for a pointer to move from a cell to its adjacent cell. If the pointer can reach the bottom-right corner of the grid within maxTime seconds, return the string 'Yes'. Otherwise, return the string 'No'. Function Description Complete the function reachTheEnd in the editor. reachTheEnd has the following parameter(s):

  • String[] grid: an array of strings representing the rows of the grid
  • int maxTime: the maximum time to complete the journey

Constraints

  • 1 ≤ rows ≤ 500
  • 1 ≤ maxTime ≤ 10⁵

Example 1

Input:

grid = ["..#", "#.##", "#..."]
maxTime = 5

Output:

"Yes"

Explanation: ..## #.## #... It will take the pointer 5 seconds to reach the bottom-right corner. As long as maxTime ≥ 5, return 'Yes'.

Example 2

Input:

grid = ["..", ".."]
maxTime = 3

Output:

"Yes"

Explanation: The grid has 2 rows and 2 columns and the time within which the pointer needs to reach the bottom-right cell is 3 seconds. Starting from the top-left cell, the pointer can either move to the top-right unblocked cell or bottom-left unblocked cell then to the bottom-right cell. It takes 2 seconds to reach the bottom-right cell on either path. Thus, the pointer reachs the bottom-right cell within the 3 seconds allowed, so the answer is "Yes" :)

Example 3

Input:

grid = [".#", "#."]
maxTime = 2

Output:

"No"

Explanation: The grid has 2 rows and 2 columns and the time within which the pointer needs to reach the bottom-right cell is 2 seconds. It can neither move to the top-right cell is 2 seconds. It can neither move to the top-right cell nor to the bottom-left cell and so the pointer cannot reach the bottom-right cell, regardless of the time constraint.

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

For example, there are n = 4 presenters scheduled for the course of the event which begins at time 0 and ends at time t = 15. The meetings start at times start = [4, 6, 7, 10] and end at times finish = [5, 7, 8, 11]. You can rearrange up to k = 2 meetings. In this case, we have 4 periods without speakers scheduled: [0-3], [5], [8-9], [11-14]. The meeting ends after hour 14. If the first meeting is shifted to an hour later, a break is created from 0 to 5 (5 hours). If the last speech is moved up to 8, it will end at 9, leaving a break from 9 to 15. There is no point in moving the middle two speeches in this case. The longest break that can be achieved is 15 - 9 = 6 hours by moving the last speech two hours earlier. Function Description Complete the function findMaximumBreakTime in the editor. findMaximumBreakTime has the following parameters:

    1. int[] start: an array of integers representing the start times of meetings
    1. int[] finish: an array of integers representing the end times of meetings
    1. int t: the total duration of the day
    1. int k: the number of meetings that can be rescheduled Returns int: the maximum break time that can be achieved by rescheduling up to k meetings

Constraints

  • 1≤n≤10⁵ (number of events)
  • 0≤k≤n (number of reschedules allowed)
  • 1≤t≤10⁹ (total duration of the day)
  • 0≤start[i]<finish[i]≤t for all i (start and end times of events)
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

There is a board with N cells (numbered from 0 to N-1) arranged in a row. The board is described by an array points and a string tokens, both of length N. The K-th cell of the string tokens is either 'T' or 'E', indicating whether the K-th cell contains a token or is empty. If the K-th cell contains a token, we assign the number of points equal to points[K]. Additionally, we score another for every pair of adjacent tokens. The goal is the total number of points we score?

Constraints

  • array points and string tokens are of the same length N;
  • N is an integer within [1, 100];
  • each element of array points is an integer within the range [1, 1,000];
  • string tokens consists only of the characters 'E' and/or 'T'.

Example 1

Input:

points = [3, 4, 5, 2, 3]
tokens = "TEETT"

Output:

9

Explanation: Cells 0, 3 and 4 contain tokens. The sum of points in these cells is 8. Also, there is one pair of adjacent cells with tokens, which result in 1 extra point. The function should return 9.

Example 2

Input:

points = [3, 2, 1, 2, 2]
tokens = "ETTTE"

Output:

7

Explanation: Cells 1, 2 and 3 contain tokens. the sum of points in these cells is 5. Also there are two pairs of adjacent cells with tokens, which results in 2 extra points. The function should return 7 :)

Example 3

Input:

points = [2, 2, 2, 2]
tokens = "TTTT"

Output:

11

Explanation: All cells contain tokens. The function should return 11 :)

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

You are given a list of products, where each product is a string. You are also given a searchWord. After each character typed, return the top k suggestions of product names that match the typed prefix. Each product also has an associated popularity score (Map) ((P.S. changed it to String[][] for FP's convenience :)). Suggestions should be returned in order of: Highest popularity score If scores are equal, return the lexicographically smaller product. You must return suggestions after each character of searchWord. Handle up to 1e5 products and optimize for performance.

Example 1

Input:

products = ["apple", "appetizer", "application", "app", "apply", "banana", "appstore"]
popularity = [["apple", "80"], ["appetizer", "70"], ["application", "90"], ["app", "90"], ["apply", "85"], ["banana", "60"], ["appstore", "90"]]
searchWord = "app"
k = 3

Output:

[["app", "application", "appstore"], ["app", "application", "appstore"], ["app", "application", "appstore"]]

Explanation: .

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

Some data scientists are building a utility to analyze palindromic trends in the DNA sequencing of a string. The palindrome transformation cost of a string is defined as the minimum number of characters that need to be changed in it so that it can be rearranged to form a palindrome. For example, the palindrome transformation cost of the string "aabcd" is 1 since we can change the last character 'd' to 'c' so that the string becomes "aabcc" that can be rearranged to "acbca" which is a palindrome. Given string dna, find the total sum of palindrome transformation cost of all the substrings of the given string. Note: A palindrome is a sequence that reads the same backward as forward, for example, sequences "z", "aba" and "aaa" are palindromes, but sequences "xy", "rank" are not. Function Description Complete the function setTotalPalindromeTransformationCost in the editor below. The function returns the total sum of palindrome transformation costs across all substrings. setTotalPalindromeTransformationCost has the following parameter:

  • dna: string ༊·° Now sending 1009th thank you to spike!

Constraints

  • 1 ≤ |dna| ≤ 2 * 10⁵
  • The string dna contains lowercase english letters only

Example 1

Input:

dna = "abca"

Output:

6

Explanation: “a", "b", "c", "a", with cost = 0 "ab", cost = 1, we change change 'b' to 'a' and it becomes "aa" which is a palindrome. "abc", cost = 1, we change 'b' to 'c' and it can be rearranged to "cac" which is a palindrome. "abca", cost = 1, we change 'b' to 'c' and it becomes "acca" which is a palindrome. "bc", cost = 1, we can change 'b' to 'c' and it becomes "cc" which is a palindrome. "bca", cost = 1, we change 'c' to 'a' and it can be rearranged to "aba" which is a palindrome. "ca", cost = 1, we change 'c' to 'a' and it becomes "aa" which is a palindrome. hence the answer is 1 + 1 + 1 + 1 + 1 + 1 = 6.

Example 2

Input:

dna = "wwwww"

Output:

0

Explanation: Given dna = "wwwww", all substrings are already palindromes with cost = 0, hence the total sum is 0.

Example 3

Input:

dna = "acbaed"

Output:

19

Explanation: "a", "c", "b", "a", "e", "d" have cost = 0 All substrings of length 2 i.e. "ac", "cb", "ba", "ae", "ed" have cost = 1, we can change either of the character to other. "acb", "cba", "bae", "aed" have cost = 1, we can change last character to first character in each of them. "acba" has cost = 1, we can change 'b' to 'a'. "acbae" has cost = 1, we can change 'c' to 'e' and it can be rearranged to "aebea" which is a palindrome. "acbaed" has cost = 2, we can change 'c' to 'e' and 'b' to 'd', then it can be rearranged to "aeddea" which is a palindrome. Similarly, "cbae", "baed" and "cbaed" have cost = 2. Hence, the answer is 5 * 1 + 4 * 1 + 1 + 1 + 4 * 2 = 19.

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

You are given a weighted graph with n nodes labeled 0 through n - 1. Each edge is represented as [u, v, w], meaning there is an edge between nodes u and v with non-negative distance w. Compute two values:

  • the length of the shortest path from start to target
  • the length of the shortest path from start to target that must pass through waypoint If a required path does not exist, use -1 for that entry. Function Description Complete the function shortestPathWithWaypoint in the editor below. shortestPathWithWaypoint has the following parameters:
  • int n: the number of nodes
  • int[][] edges: undirected weighted edges [u, v, w]
  • int start: the starting node
  • int target: the destination node
  • int waypoint: the node that the constrained path must visit Returns int[]: a length-2 array [bestDistance, bestDistanceViaWaypoint].

Constraints

  • 1 ≤ n ≤ 2 * 10⁵
  • 0 ≤ edges.length ≤ 3 * 10⁵
  • 0 ≤ w ≤ 10⁹
  • All edge weights are non-negative.
  • If no path exists for a requested scenario, return -1 for that entry.

Example 1

Input:

n = 5
edges = [[0, 1, 2], [1, 2, 3], [0, 3, 10], [2, 4, 1], [3, 4, 2], [1, 3, 2]]
start = 0
target = 4
waypoint = 1

Output:

[6, 6]

Explanation: The shortest path from 0 to 4 is 0 -> 1 -> 2 -> 4 with total cost 6. That path already passes through the mandatory waypoint 1, so both answers are 6.

Example 2

Input:

n = 4
edges = [[0, 1, 1], [1, 3, 1], [0, 2, 1]]
start = 0
target = 3
waypoint = 2

Output:

[2, -1]

Explanation: The unconstrained shortest path is 0 -> 1 -> 3 with cost 2. There is no path from 2 to 3, so no valid route can pass through the waypoint.

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

Imagine you have a special keyboard with all keys in a single row. The layout of characters on a keyboard is denoted by a string keyboard of length 26. Initially your finger is at index 0. To type a character, you have to move your finger to the index of the desired character. The time taken to move your finger from index i to index j is abs(j - i). Given a string keyboard that describe the keyboard layout and a string text, return an integer denoting the time taken to type string text. Function Description Complete the function calculateTime in the editor. calculateTime has the following parameters:

  • String keyboard: a string that describes the keyboard layout
  • String text: the text to be typed Returns int: the time taken to type the string text

Constraints

  • length of keyboard</code

Example 1

Input:

keyboard = "abcdefghijklmnopqrstuvwxy"
text = "cba"

Output:

4

Explanation: Initially your finger is at index 0. First you have to type 'c'. The time taken to type 'c' will be abs(2 - 0) = 2 because character 'c' is at index 2. The second character is 'b' and your finger is now at index 2. The time taken to type 'b' will be abs(1 - 2) = 1 because character 'b' is at index 1. The third character is 'a' and your finger is now at index 1. The time taken to type 'a' will be abs(0 - 1) = 1 because character 'a' is at index 0. The total time will therefore be 2 + 1 + 1 = 4.

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

Design a prototype for a friend recommendation system for a social media platform. You have n users labeled from 1 to n, and m friendships represented as a 2D array called friendships. Each entry friendship[i] is a connection between users friendship[i][0] and friendship[i][1]. For any user y, another user x is recommended as a friend if x and y are not currently friends and have the highest number of mutual friends (friends in common). In case of ties (multiple users x with the same number of mutual friends), recommend the user with the smallest index. Given n and friendships, determine the friend recommendation for each user from 1 to n. If no recommendation can be made, return -1 for that user.

Constraints

  • n ≤ 10⁵
  • m ≤ 2.5 * 10⁵
  • Each user has at most 15 friends.

Example 1

Input:

n = 3
m = 2
friendships = [[0, 1], [0, 2]]

Output:

[-1, 2, 1]

Explanation: Since 0 is friends with both users, no recommendation can be made. As common friends of 0, 1 and 2 can be recommended to one another.

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

You are given an array A of N integers. You can split the array into two non-empty parts, left and right, sort the elements in each part independently and join them back together. For example, given array A = [1, 3, 2, 4], you can split it in the following three ways:

  • left = [1], right = [3, 2, 4]. Sorting the elements and joining the parts back together results in the array: [1, 2, 3, 4].
  • left = [1, 3], right = [2, 4]. Resulting sorted and rejoined array: [1, 3, 2, 4].
  • left = [1, 3, 2], right = [4]. Resulting sorted and rejoined array: [1, 2, 3, 4]. Your task is to find the number of ways of splitting the array into two parts such that, after sorting the two parts and rejoining them into a single array, the resulting array will be sorted in non-decreasing order. For the array shown above, the answer is 2: the first and third splits result in a sorted array. Function Description Write a function: class Solution { public int solution(int[] A); } which, given an array A of length N, returns the number of different ways of obtaining a sorted array by applying the procedure described above.

Constraints

  • N is an integer within the range [2..100,000];
  • each element of array A is an integer within the range [1..1,000,000,000].

Example 1

Input:

A = [1, 3, 2, 4]

Output:

2

Explanation: The function should return 2, as there are two ways to split the array into two parts that result in a sorted array after sorting and rejoining: • left = [1], right = [3, 2, 4] • left = [1, 3, 2], right = [4]

Example 2

Input:

A = [3, 2, 10, 9]

Output:

1

Explanation: The function should return 1, as there is only one way to split the array into two parts that result in a sorted array after sorting and rejoining: • left = [3, 2], right = [10, 9]

Example 3

Input:

A = [5, 5, 5]

Output:

2

Explanation: The function should return 2, as there are two ways to split the array into two parts that result in a sorted array after sorting and rejoining: • left = [5], right = [5, 5] • left = [5, 5], right = [5]

Example 4

Input:

A = [3, 1, 2]

Output:

0

Explanation: The function should return 0, as there are no ways to split the array into two parts that would result in a sorted array after sorting and rejoining.

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

Given an int array nums of length n. Split it into strictly decreasing subsequences. Output the min number of subsequences you can get by splitting.

Constraints

Unknown yet. If you happen to know about it, feel free to lmk! TYSM ~3~

Example 1

Input:

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

Output:

3

Explanation: You can split this array into: [5, 2, 1], [4, 3], [6]. And there are 3 subsequences you get. Or you can split it into [5, 4, 3], [2, 1], [6]. Also 3 subsequences. But [5, 4, 3, 2, 1], [6] is not legal because [5, 4, 3, 2, 1] is not a subsequence of the original array.

Example 2

Input:

nums = [2, 9, 12, 13, 4, 7, 6, 5, 10]

Output:

4

Explanation: You can split the array into: [2], [9, 4], [12, 10], [13, 7, 6, 5].

Example 3

Input:

nums = [1, 1, 1]

Output:

3

Explanation: Because of the strictly descending order you have to split it into 3 subsequences: [1], [1], [1].

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

The source mentioned that the actual question asked during the phone screen was "very" similar to LeetCode 68 (Text Justification). Another question asked was: Given a text dataset that needs to be formatted into a two-column table on a fixed-width page, determine the optimal column size that minimizes the overall table height. This was a follow-up question, and I provided a solution using Binary Search. Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified, and no extra space is inserted between words. Note:

  • A word is defined as a character sequence consisting of non-space characters only.
  • Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.
  • The input array words contains at least one word.

Constraints

  • 1 ≤ words.length ≤ 300
  • 1 ≤ words[i].length ≤ 20
  • words[i] consists of only English letters and symbols.
  • 1 ≤ maxWidth ≤ 100
  • words[i].length ≤ maxWidth

Example 1

Input:

words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16

Output:

["This is an", "example of text", "justification. "]

Explanation: The words are arranged such that each line has exactly 16 characters and is fully justified.

Example 2

Input:

words = ["What","must","be","acknowledgment","shall","be"]
maxWidth = 16

Output:

["What must be", "acknowledgment ", "shall be "]

Explanation: Note that the last line is "shall be " instead of "shall be", because the last line must be left-justified instead of fully-justified. Note that the second line is also left-justified because it contains only one word.

Example 3

Input:

words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"]
maxWidth = 20

Output:

["Science is what we", "understand well", "enough to explain to", "a computer. Art is", "everything else we", "do "]

Explanation: The words are arranged such that each line has exactly 20 characters and is fully justified.

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

Design the move-processing logic for a generalized Tic-Tac-Toe game. There are k players and an n x n board. Players take turns placing their own mark on an empty cell. Player numbers are 1 through k. A player wins as soon as they have at least 3 consecutive marks in a straight line. The line may be horizontal, vertical, diagonal, or anti-diagonal. This winning length is always 3, even when n is larger than 3. Given the move list, return the game status after each move:

  • "Game Over" if the move is attempted after a winner already exists.
  • "Player X won" if player X wins on that move.
  • "Draw" if the board becomes full and nobody has won.
  • "In Progress" otherwise. All moves in the input are within board bounds. If a move targets an already occupied cell before the game is over, leave the board unchanged and return "Invalid Move" for that move.

Constraints

  • 1 ≤ k ≤ 10
  • 3 ≤ n ≤ 10³
  • 1 ≤ moves.length ≤ min(n² + 5, 10⁵)
  • Each move is encoded as [player, row, col], where 1 ≤ player ≤ k and 0 ≤ row, col < n.

Example 1

Input:

k = 2
n = 3
moves = [[1,0,0],[2,1,0],[1,0,1],[2,1,1],[1,0,2]]

Output:

["In Progress","In Progress","In Progress","In Progress","Player 1 won"]

Explanation: Player 1 completes three consecutive marks across the top row.

Example 2

Input:

k = 3
n = 4
moves = [[1,0,0],[2,0,1],[3,3,3],[1,1,1],[2,1,0],[3,2,1],[1,2,2]]

Output:

["In Progress","In Progress","In Progress","In Progress","In Progress","In Progress","Player 1 won"]

Explanation: Player 1 completes the diagonal segment (0,0), (1,1), (2,2).

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

Given two strings of equal length made up of 'x', 'y', and 'z', with no consecutive characters the same, determine the minimum number of operations needed to transform the first string into the second. In one operation, you can change any character in the first string, ensuring no consecutive characters become identical.

Example 1

Input:

str1 = "zxyz"
str2 = "zyxz"

Output:

6

Explanation: zxyz -> yyxz -> yyzz -> yzxz -> zxxz -> zyxz -> zyxz

Example 2

Input:

str1 = "xzyzyzyzxyz"
str2 = "xzyzyzyzyxy"

Output:

15

Explanation: The minimum number of operations needed to transform the first string into the second is 15.

Example 3

Input:

str1 = "xyyxyxyxyy"
str2 = "xzyxyzyxzx"

Output:

13

Explanation: The minimum number of operations needed to transform the first string into the second is 13.

Example 4

Input:

str1 = "xyyxyzzyxy"
str2 = "zyzyzyzyzyz"

Output:

9

Explanation: The minimum number of operations needed to transform the first string into the second is 9.

Example 5

Input:

str1 = "xzxyxyzzyxyz"
str2 = "zyzyzyzyzyzy"

Output:

20

Explanation: The minimum number of operations needed to transform the first string into the second is 20.

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

Write a tool which supports substitutions of templates by other strings. Function Description Complete the function substituteTemplates in the editor. substituteTemplates has the following parameters:

    1. Map substitutions: a map containing the substitutions
    1. String template: the template string to be resolved Returns String: the resolved template

Example 1

Input:

substitutions = {"X" -> "123", "Y" -> "456", "Z" -> "abc"}
template = "%X%_%Y%"

Output:

"123_456"

Explanation: The template %X%_%Y% should be resolved by replacing %X% with 123 and %Y% with 456, resulting in 123_456.

Example 2

Input:

substitutions = {"X" -> "123", "Y" -> "456", "Z" -> "abc%Y%"}
template = "%X%_%Y%_%Z%"

Output:

"123_456_abc456"

Explanation: The template %X%_%Y%_%Z% should be resolved by replacing %X% with 123, %Y% with 456, and %Z% with abc%Y% which further resolves to abc456. The final result is 123_456_abc456.

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

解锁全部 76 道题的解法

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

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

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