OAmaster
— / 36已做

A data analyst is given an array representing data for n days. The analyst performs k updates on the data, where each update is of the form [l, r]. This indicates that the elements of the array from index l to index r (inclusive) are negated.

Given the initial data array and k updates, return the final data array after all updates. Note: 1-based indexing is used.

Example

data = [1, 2, 3, 4, 5], updates = [[1, 3], [2, 4]]
After [1,3]: [-1, -2, -3, 4, 5]
After [2,4]: [-1, 2, 3, -4, 5]
Answer: [-1, 2, 3, -4, 5]

Constraints

  • 1 <= n, k <= 10⁶
  • |data[i]| <= 10⁹

解法

XOR 翻转的差分:每次更新 [l,r] 时翻转 l-1r 处的奇偶位。一次扫描,按当前 XOR 奇偶决定是否取反。复杂度 O(n + k)

def get_final_data(data: list[int], updates: list[list[int]]) -> list[int]:
    n = len(data)
    flip = [0] * (n + 1)
    for l, r in updates:
        flip[l - 1] ^= 1
        flip[r] ^= 1
    cur = 0
    out = []
    for i in range(n):
        cur ^= flip[i]
        out.append(-data[i] if cur else data[i])
    return out
class Solution {
    static long[] getFinalData(long[] data, int[][] updates) {
        int n = data.length;
        int[] flip = new int[n + 1];
        for (int[] u : updates) {
            flip[u[0] - 1] ^= 1;
            flip[u[1]] ^= 1;
        }
        long[] out = new long[n];
        int cur = 0;
        for (int i = 0; i < n; i++) {
            cur ^= flip[i];
            out[i] = cur == 1 ? -data[i] : data[i];
        }
        return out;
    }
}
#include <vector>
using namespace std;

vector<long long> getFinalData(vector<long long>& data, vector<vector<int>>& updates) {
 int n = data.size();
 vector<int> flip(n + 1, 0);
 for (auto& u : updates) {
 flip[u[0] - 1] ^= 1;
 flip[u[1]] ^= 1;
 }
 vector<long long> out(n);
 int cur = 0;
 for (int i = 0; i < n; i++) {
 cur ^= flip[i];
 out[i] = cur ? -data[i] : data[i];
 }
 return out;
}

You are given a computer network with n servers numbered from 1. Each server has a security value sec[i] (positive or negative). A hacker starts at one of these servers and jumps through the network. From node x, the hacker can jump to node (x + k). If (x + k) exceeds n, the hacker's attack ends. The hacker's goal is to maximize the sum of the security values of the compromised servers (initially 0 with 0 servers).

Choose the optimal starting node and return the maximum security value sum.

Example

sec = [2, -3, 5, -1, 4], k = 2
Start 0: visit 0,2,4 -> running sums 2, 7, 11; best 11.
Start 1: visit 1,3 -> running sums -3, -4; best 0.
Answer: 11

解法

数组按步长 k 分成 k 条独立链。对每个起始偏移,从 start 起按步长 k 跑 Kadane 风格的最大前缀和,整体取最大(全负则取 0)。复杂度 O(n)

def gain_max_value(sec: list[int], k: int) -> int:
    n = len(sec)
    best = 0
    for start in range(k):
        cur = local_best = 0
        i = start
        while i < n:
            cur += sec[i]
            if cur > local_best: local_best = cur
            i += k
        if local_best > best: best = local_best
    return best
class Solution {
    static long gainMaxValue(int[] sec, int k) {
        int n = sec.length;
        long best = 0;
        for (int start = 0; start < k; start++) {
            long cur = 0, localBest = 0;
            for (int i = start; i < n; i += k) {
                cur += sec[i];
                if (cur > localBest) localBest = cur;
            }
            if (localBest > best) best = localBest;
        }
        return best;
    }
}
#include <vector>
using namespace std;

long long gainMaxValue(vector<int>& sec, int k) {
 int n = sec.size();
 long long best = 0;
 for (int start = 0; start < k; start++) {
 long long cur = 0, localBest = 0;
 for (int i = start; i < n; i += k) {
 cur += sec[i];
 if (cur > localBest) localBest = cur;
 }
 if (localBest > best) best = localBest;
 }
 return best;
}

A shop has n types of items, where the quantity of the i-th item is denoted by quantity[i]. The items are split into two consignments at some j (1 ≤ j < n): first contains [1..j], second contains [j+1..n]. The shopkeeper wants the two consignments' total quantities equal, and can adjust any item's quantity by ±1 any number of times (must stay positive). Find the minimum operations.

  • quantity = [1, 4, 4]1
  • quantity = [3, 3, 6, 3, 9]0
  • quantity = [4, 5, 7]2

解法

每次 ±1 操作使两段差变化 1,最少操作数 = 所有合法分割点上 |prefix - (total - prefix)| 的最小值。一次扫描前缀和即可。复杂度 O(n)

def get_minimum_operations(quantity: list[int]) -> int:
    total = sum(quantity)
    pref = 0
    best = float('inf')
    for j in range(len(quantity) - 1):
        pref += quantity[j]
        diff = abs(pref - (total - pref))
        best = min(best, diff)
    return best
class Solution {
    static long getMinimumOperations(int[] quantity) {
        long total = 0;
        for (int x : quantity) total += x;
        long pref = 0, best = Long.MAX_VALUE;
        for (int j = 0; j < quantity.length - 1; j++) {
            pref += quantity[j];
            best = Math.min(best, Math.abs(pref - (total - pref)));
        }
        return best;
    }
}
#include <vector>
#include <climits>
#include <cstdlib>
#include <algorithm>
using namespace std;

long long getMinimumOperations(vector<int>& quantity) {
 long long total = 0;
 for (int x : quantity) total += x;
 long long pref = 0, best = LLONG_MAX;
 for (int j = 0; j < (int)quantity.size() - 1; j++) {
 pref += quantity[j];
 best = min(best, llabs(pref - (total - pref)));
 }
 return best;
}

Given an array of numbers, find the 0-based index of the smallest array element (the pivot) where the sum of all elements to the left and to the right are equal. The array may not be reordered. Function Description Complete the function balancedSum in the editor with the following parameter(s): int arr[n]: an array of integers Returns int: the 0-based index of the pivot Constraints

  • 3≤n≤10⁵
  • 1≤arr[i]≤2×10⁴, where 0≤i Couldn't do it without the help from an incredible friend!

Example 1

Input:

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

Output:

3

Explanation: The sum of the first three elements is 1 + 2 + 3 = 6. The value of the last element is 6. Using zero-based indexing, arr[3]=4 is the pivot between these two subarrays. Return the index of the pivot, 3.

Example 2

Input:

arr = [1, 2, 3, 3]

Output:

2

Explanation: The sum of the first two elements, 1 + 2 = 3. The value of the last element is 3. Using 0-based indexing, arr[2] = 3 is the pivot between these two subarrays. The index of the pivot is 2.

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

A quantitative trading firm aims to develop a tool to track the net profit/loss of the firm at any point in time. This tool processes a list of events, where each event falls into one of four categories: BUY stock quantity: Indicates the purchase of quantity shares of stock at the market price. SELL stock quantity: Indicates the sale of quantity shares of stock at the market price. CHANGE stock price: Indicates a change in the market price of stock by price amount, which can be positive or negative. QUERY: Requests the net profit/loss from the start of trading until the current time. The tool should return a list of numbers corresponding to each QUERY event. Function Description Complete the function calculateNetProfit in the editor. calculateNetProfit has the following parameter:

  • String[] events: an array of strings describing the events Returns long[]: the answers to the "QUERY" events My deepest, sincere, and boundless gratitude to an amazing friend for all their help.

Constraints

  • 1 ≤ n ≤ 10⁵
  • | events[] | ≤ 21
  • For query, SELL stock quantity, it is guaranteed that there are enough shares owned.
  • 1 ≤ quantity ≤ 10³
  • The absolute value of a change in the price of any stock at any event will not exceed 10³.

Example 1

Input:

events = ["BUY googl 20", "BUY aapl 50", "CHANGE googl 6", "QUERY", "SELL aapl 10", "CHANGE aapl 2", "QUERY"]

Output:

[0, 0]

Explanation: Hallo ~ Output is just placeholder, but the example input is complete~ As alwasy, will update more once come across more sources on the internet...

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

Given an integer denoting a total number of wheels, find the number of different ways to choose a fleet of vehicles from an infinite supply of two-wheeled and four-wheeled vehicles such that the group of chosen vehicles has that exact total number of wheels. Two ways of choosing vehicles are considered to be different if and only if they contain different numbers of two-wheeled or four-wheeled vehicles. For example, if our array wheels = [4,5,6] our return array would be res = [2, 0, 2]. Case by case, we can have 1 four-wheel or 2 two-wheel to have 4 wheels. We cannot have 5 wheels. We can have 1 four-wheel and 1 two-wheel or 3 two-wheel vehicles in the final case. Function Description Complete the function chooseFleets in the editor below. The function should return an array of integers representing the answer for each wheels[i]. chooseFleets has the following parameter(s):

  • wheels[wheels[0],...wheels[n-1]]: an array of integers

Constraints

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

A server maintains a pool of processing threads. The input array describes events in chronological order.

  • A positive value adds that many threads to the pool.
  • -1 means a request arrives. Each thread can serve at most one request and is then destroyed. If a request arrives when no threads are available, that request is dropped. Return the number of dropped requests.

Constraints

  • 1 ≤ n ≤ 10⁵
  • server[i] = -1 or 1 ≤ server[i] ≤ 10⁴

Example 1

Input:

server = [1, -1, -1, 1]

Output:

1

Explanation: The first request consumes the only available thread. The second request arrives when the pool is empty, so it is dropped.

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

Given a range of integers, determine how many numbers have no repeating digits. Example: n = 80, m = 120 The lower and upper bounds are inclusive, so there are 120 - 79 = 41 values in the range :) Numbers without repeating characters are normal weight and others are bold. The two columns to the ight are the valid number counts per row (normal weight :) and invalid number counts (bold :) Ther are 27 numbers with no repeating digits, and 14 other numbers in the range. Print 27. Function Description Complete the function countNumbers in the editor below. countNumbers has the following parameter(s):

  • int arr[q][2]: integer pairs representing inclusive lower (n) and upper (m) range limits Print For each pair arr[i], print the number of integers in the inclusive range that qualify. There is no value to return from the function. Tomtom's note: This question is a bit special. The original question doesn't require a return type, but I’ve made the return type int[]. If the return type were void, you wouldn’t be able to practice it here.

Constraints

  • 1 ≤ q ≤ 10⁵
  • 1 ≤ n ≤

Example 1

Input:

arr = [[1, 20], [9, 19]]

Output:

[19, 10]

Explanation: Row 0 [1, 20] The set of qualifying numbers in the inclusive range between n[0] = 1 and m[0] = 20 is {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20}. This gives us c[0] = 19. Row 1 [9, 19] The set of qualifying numbers in the inclusive range between n[1] = 9 and m[1] = 19 is {9, 10, 12, 13, 14, 15, 16, 17, 18, 19}. This gives us c[1] = 10.

Example 2

Input:

arr = [[7, 8], [52, 80], [9, 84], [57, 64], [74, 78]]

Output:

[2, 26, 47, 8, 4]

Explanation: Row 0 [7, 8] The set of qualifying numbers in the inclusive range between n[0] = 7 and m[0] = 8 is {7, 8}. This gives us c[0] = 2. Row 1 [52, 80] The set of qualifying numbers in the inclusive range between n[1] = 52 and m[1] = 80 is {52, 53, 54, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 78, 79, 80}. This gives us c[1] = 26. Row 2 [9, 84] The set of qualifying numbers in the inclusive range between n[2] = 9 and m[2] = 84 is {9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 78, 79, 80, 81, 82, 83}. This gives us c[2] = 47. Row 3 [57, 64] The set of qualifying numbers in the inclusive range between n[3] = 57 and m[3] = 64 is {57, 58, 59, 60, 61, 62, 63, 64}. This gives us c[3] = 8. Row 4 [74, 78] The set of qualifying numbers in the inclusive range between n[3] = 74 and m[3] = 78 is {74, 75, 76, 78}. This gives us c[4] = 4.

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

Sometimes it is necessary to filter a signal by frequency, e.g. to reduce noise outside of the expected frequency range. Filters can be stacked, allowing only the frequencies within the range allowed by all filters to get through. For example, three filters with ranges of (10, 17), (13, 15) and (13, 17) will only allow signals between 13 and 15 through. The only range that all filters overlap is (13, 15). Given n signals' frequencies and a series of m filters that let through frequencies in the range x to y, inclusive, determine the number of signals that will get through the filters. There will be only one range where all the filters overlap. Function Description Complete the function countSignals in the editor below. countSignals has the following parameter(s): int frequencies[n]: the frequencies of the signals sent through the filters int filterRanges[m][2]: the lower and upper frequency bounds for each filter Returns int: the number of signals that pass through all filters

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ frequencies[i] ≤ 10⁹
  • 1 ≤ m ≤ 10⁵
  • 1 ≤ filterRanges[j][k] ≤ 10⁹
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

There is a hackathon organized by HackerRank which has 2 separate tracks, healthcare and e-commerce. For track 1, the required team size is teamSize_1, while for track 2, the required team size is teamSize_2. The total number of participants is p. Find the minimum number of teams into which the participants can be divided such that each participant belongs to exactly one team (either of track 1 or track 2), and each team has a size equal to either teamSize_1 or teamSize_2. If no such division is possible, return -1. Function Description Complete the function countTeams in the editor. The function countTeams has the following parameters:

  • int teamSize_1: the number of participants in teams of track 1
  • int teamSize_2: the number of participants in teams of track 2
  • int p: the total number of participants Returns int: the minimum number of teams into which the participants can be divided

Constraints

  • 1 ≤ teamSize_1, teamSize_2 ≤ 10⁵
  • 1 ≤ p ≤ 10⁵

Example 1

Input:

teamSize_1 = 3
teamSize_2 = 4
p = 7

Output:

2

Explanation: Optimally there is 1 team of 3 and 1 team of 4. The minimum number of teams is 2.

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

Given an array of integers, the goal is to make all the elements in the array have equal values by applying some number of operations. The rules of the operations are: To apply an operation, one needs to choose a prefix of the array and an integer x (x can be negative). In this operation, add x to each element inside this prefix. The cost of this operation is |x| (Absolute value of x). For example, if the array is [1, 4, 2, 1] and the prefix of length 2 and x = -3 are chosen, the array would now become [-2, 1, 2, 1] and the total cost of this operation would be |x| = |-3| = 3. The total cost is the sum of costs of each operation applied. Find the minimum total cost of making all the elements in the array have equal value. Note: It is guaranteed that there always exists a series of operations by which all the elements in any array can be equal. These operations can be applied any number of times. Function Description Complete the function findMinimumCost in the editor below. findMinimumCost has the following parameter:

  • List<Integer> arr: an array of integers

Constraints

N/A

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

Consider two arrays of integers, a[n] and b[n]. What is the maximum number of pairs that can be formed where a[i] > b[j]? Each element can be in no more than one pair. Find the maximum number of such possible pairs. Function Description Complete the function findNumOfPairs in the editor below. findNumOfPairs has the following parameters:

  • int a[n]: an array of integers
  • int b[n]: an array of integers Returns int: the maximum number of pairs possible

Constraints

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

Example 1

Input:

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

Output:

2

Explanation: Two ways the maximum number of pairs can be selected:

  • {a[1], b[0]}={2, 1} and {a[2], b[2]}={3, 1} are valid pairs.
  • {a[1], b[0]}={2, 1} and {a[2], b[1]}={3, 2} are valid pairs. No more than 2 pairs can be formed, so return 2.

Example 2

Input:

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

Output:

3

Explanation: Valid paris are {a[1], b[2]}, {a[2], b[3]}, {a[3], b[4]} or {2, 1}, {3, 1}, {4, 1}

Example 3

Input:

a = [2, 3, 3]
b = [3, 4, 5]

Output:

0

Explanation: Since all the elements of b are greater than each element of a, no pair can be formed T~T

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

Stacey is coordinating a beach clean-up project with her university's Women in STEM Outreach branch. The beach is covered with tin cans of varying weights arranged in a single line, indexed from 0 to n-1. Stacey uses a scooper that can pick up three adjacent cans at a time. For each selection:

  • She identifies the three adjacent cans with weight w
  • She uses the scooper to pick up the three cans with w
  • She removes them from the beach
  • She continues this process until there are no cans left on the beach For each selection, all cans have the lightest weight. Stacey selects the one with the smallest index that contains three adjacent cans with the lightest weight. Determine the sum of the weights of the three cans she picks in each selection. Function Description Complete the function findSumWeight in the editor with the following parameter:
  • cans: array of the cans on the beach
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given an array arr of n integers, a sequence of n-1 operations must be performed on the array. In each operation, Remove the minimum and maximum elements from the current array and add their sum back to the array. The cost of an operation, cost = ceil((minimum_element + maximum_element) / (maximum_element-minimum_element + 1)). Find the total cost to reduce the array to a single element.

Example 1

Input:

arr = [2, 3, 4, 5, 7]

Output:

8

Explanation: The possible sequence of operations are: Choose 2 and 7, the cost = ceil((2 + 7) / (7 - 2 + 1)) = ceil(9 / 6) = 2. Remove 2 and 7, append 9, arr = [3, 4, 5, 9], total_cost = 2. Choose 3 and 9, the cost = ceil((3 + 9) / (9 - 3 + 1)) = ceil(12 / 7) = 2, arr = [4, 5, 12], total_cost = 2 + 2 = 4. Choose 4 and 12, the cost = ceil((4 + 12) / (12 - 4 + 1)) = ceil(16 / 9) = 2, arr = [5, 16], total_cost = 4 + 2 = 6. Choose 5 and 16, the cost = ceil((5 + 16) / (16 - 5 + 1)) = ceil(21 / 12) = 2, arr = [21], total_cost = 6 + 2 = 8. Return the total cost, 8.

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

Stacey is coordinating a beach clean-up event with her university's Women in STEM Charity branch. The beach is covered with tin cans of varying weights arranged in a single line, indexed from 0 to n-1. Stacey uses a scooper that can pick up three adjacent cans at a time. For each selection: She identifies the lightest remaining can, with weight w She uses the scooper to pick up that can along with its two adjacent cans (or fewer if at the edge) She continues this process until there are no cans left on the beach If multiple cans have the lightest weight, Stacey selects the one with the smallest index. If a can has fewer than two adjacent cans, she removes the available adjacent cans. Determine the sum of the weights of the lightest cans she picks in each selection. Function Description Complete the function findTotalWeight in the editor with the following parameters:

  • int cans[n]: the weights of the cans on the beach
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given a document as an array of strings.

  • A chapter is any line that starts with # .
  • A section is any line that starts with ## and belongs to the most recent chapter.
  • All other lines should be ignored. Build a table of contents using chapter numbers 1, 2, 3, ... and section numbers such as 1.1, 1.2, 2.1, and so on. Return the result as a String[].

Constraints

  • 1 ≤ text.length ≤ 1000
  • 1 ≤ text[i].length ≤ 100
  • The first valid heading in the document is guaranteed to be a chapter.

Example 1

Input:

text = ["# Algorithms", "This chapter covers the most basic algorithms.", "## Sorting", "Quicksort is fast and widely used in practice", "Merge sort is a deterministic algorithm", "## Searching", "DFS and BFS are widely used graph searching algorithms", "Some variants of DFS are also used in game theory applications", "# Data Structures", "This chapter is all about data structures", "It's a draft for now and will contain more sections in the future", "# Binary Search Trees"]

Output:

["1. Algorithms", "1.1. Sorting", "1.2. Searching", "2. Data Structures", "3. Binary Search Trees"]

Explanation: Only chapter and section markers contribute to the table of contents, and sections are numbered relative to the latest chapter.

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

Given a string s with uppercase English letters, remove all occurrences of the string AWS until no more remain. After each removal, the prefix and suffix strings are concatenated. Return the final string. If the final string is empty, return "-1" as a string. Function Description Complete the function getFinalString in the editor below. The function getFinalString has the following parameter:

  • string s[n]: a string of uppercase English characters Returns string: the string, after removing all occurrences of "AWS" from the given string or "-1"

Constraints

  • 1 ≤ |s| ≤ 10⁵
  • The string contains only uppercase English letters.

Example 1

Input:

s = "AWAWSSG"

Output:

"G"

Explanation: AWAWSSGAWSGG Return the final string, G.

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

Given a number num, two adjacent digits can be swapped if their parity is the same, that is, both are odd or both are even. For example, (5, 9) have the same parity, but (6,9) do not. Find the largest number that can be created. The swap operation can be applied any number of times. Function Description Complete the function getLargestNumber in the editor below. getLargestNumber has the following parameter:

  • string num: a string of digits Returns strings: the largest number that can be created

Constraints

  • 1 ≤ length of num ≤ 10⁵
  • num consists of digits 0-9 only.

Example 1

Input:

num = "7596801"

Output:

"9758601"

Explanation: Let num = "7596801".

  • Swap 5 and 9 → "7956801"
  • Swap 7 and 9 → "9756801"
  • Swap 6 and 8 → "9758601" The largest value possible is "9758601".

Example 2

Input:

num = "0082663"

Output:

"866203"

Explanation: No enough reference for now. Will add once find any useful info :)

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

A control device has 4 buttons that can be used to move a character around a screen in 4 directions: Up (U), Down (D), Left (L), and Right (R). The movement needs to be optimized by deleting unnecessary instructions while maintaining the same destination. Given the original set of instructions, what is the maximum number of instructions that can be deleted and still have the character reach the destination? Note: The instructions that are deleted do not need to be contiguous. Function Description Complete the function getMaxDeletions in the editor below. getMaxDeletions has the following parameter:

  • string S: the original instructions that were programmed Returns int: the maximum number of instructions that can be deleted from S while maintaining the destination

Constraints

  • 1 ≤ n ≤ 10⁵
  • S contains only the characters 'U', 'D', 'L', and 'R'.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given a collection of time intervals, [start, end], merge and return the overlapping intervals sorted in ascending order of their start times. Function Description Complete the function getMergedIntervals in the editor below. getMergedIntervals has the following parameters:

  • int intervals[[n][2]]: the time intervals Returns int[][2]: the merged intervals in sorted order

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ intervals[i][2] ≤ 10⁹
  • intervals[i][0] ≤ intervals[i][1] for all i.

Example 1

Input:

intervals = [[7, 7], [2, 3], [6, 11], [1, 23]]

Output:

[[1, 3], [6, 11]]

Explanation: an educated guess - The interval [1, 2] merges with [2, 3] while [7, 7] merges with [6, 11]. There are no more overlapping intervals. The answer is [[1, 3], [6, 11]].

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

Given a string, seq, that consists of the characters 'A' and 'B' only, in one move, delete either an "AB" or a "BB" substring and concatenate the remaining substrings. Find the minimum possible length of the remaining string after performing any number of moves. Note: A substring is a contiguous subsequence of a string. Function Description Complete the function getMinLength in the editor below. getMinLength has the following parameter(s):

  • string seq: the string Returns int: the minimum possible length of the remaining string

Constraints

  • 1 ≤ |seq| ≤ 2 * 10⁵
  • The string only contains characters 'A' and 'B'.

Example 1

Input:

seq = "BABBA"

Output:

1

Explanation: Using 0-based indexing, the following moves are optimal.

  • Delete the substring "AB" starting at index 1. "BABBA" → "BBA"
  • Delete the substring "BB" starting at index 0. "BBA" → "A" There are no more moves, so the minimum possible length of the remaining string is 1.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given a set of n tasks, the i^th (0 ≤ i Function Description Complete the function getMinMachines in the editor. getMinMachines has the following parameters:

  • int start[n]: the start times of tasks
  • int end[n]: the end times of tasks Returns int: the minimum number of machines required to run all the tasks

Constraints

  • 1 ≤ n ≤ 2 * 10⁵
  • 1 ≤ start[i] ≤ end[i] ≤ 10⁹

Example 1

Input:

start = [1, 8, 3, 9, 6]
end = [7, 9, 6, 14, 7]

Output:

3

Explanation: Consider the following task schedule. Times in parentheses are the inclusive start and end times for each job.

  • Machine 1: [(1, 7), (8, 9)]
  • Machine 2: [(3, 6), (9, 14)]
  • Machine 3: [(6, 7)] Here, the number of machines required is 3.

Example 2

Input:

start = [2, 1, 6, 5, 8]
end = [5, 8, 3, 6, 12]

Output:

3

Explanation:

  • Machine 1: [(2, 8)] (this is my educated guess :)
  • Machine 2: [(1, 3)] (this is my educated guess :)
  • Machine 3: [(5, 6)] (this comes from the original reference :) If you find anything wrong, plssss lmk!! Many thanks in adavance!

Example 3

Input:

start = [2, 2, 2, 2]
end = [5, 5, 5, 5]

Output:

4

Explanation:

  • Machine 1: [(2, 5)]
  • Machine 2: [(2, 5)]
  • Machine 3: [(2, 5)]
  • Machine 4: [(2, 5)]
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Starting from 0, add 1, then multiply by 2 three times. It takes a minimum of 4 operations to get to 8, so store 4 in index 0 of the return array. Function Description Complete the function getMinOperations in the editor with the following parameter(s): kValues[n]: the values to match Returns int[n]: answers to a list of queries in the given order Constraints

  • 1 ≤ n ≤ 10⁴
  • 0 ≤ kValues ≤ 10¹⁶

Example 1

Input:

kValues = [5, 3]

Output:

[4, 3]

Explanation: 0. To get from 0 to kValues[0] = 5, ADD_1 → MULTIPLY_2 → MULTIPLY_2 → ADD_1 to get 0 + 1 → 1 × 2 → 2 × 2 → 4 + 1 = 5. Because it took four operations, store 4 in index 0 of the return array.

  1. To get from 0 to kValues[1] = 3, ADD_1 → MULTIPLY_2 → ADD_1 to get 0 + 1 → 1 × 2 → 2 + 1 = 3. Because it took three operations, store 3 in index 1 of the return array.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

The owner of HackerMall loves organized items. A row of items is organized if the parity (even or odd) is different for each adjacent stack of items. To organize the row, half of the items in any stack can be removed. This can happen as many times and on as many stacks as is required. Determine the minimum number of operations needed to organize a row. More formally, given an array items[] of integer of length n, the array is organized if for each x less than n-1, items[x] mod 2 ≠ items[x + 1] mod 2. A mod B is the remainder of A divided by B. In one operation, the owner can choose an element and divide it by 2. That is, if one chooses index x then do items[x] = floor( items[x]/2). The goal is to return the minimum number of operations that one needs to perform to organize the array. Function Description Complete the function getMinimumOperations in the editor below. getMinimumOperations has the following parameter(s): int items[n]: a row of stacks of items Returns int the minimum number of operations needed to organize the array

Constraints

  • `1

Example 1

Input:

items = [4, 10, 10, 6, 2]

Output:

2

Explanation: The array is not organized since, for example, items[2] mod 2 = items[3] mod 2. One way to organize the array is shown using 1-based indexing.

  • Choose the 2nd index and divide it by 2; the new array is [4, 5, 10, 6, 2].
  • Choose the 4th index and divide it by 2; the new array is [4, 5, 10, 3, 2]. [4, 5, 10, 3, 2] is an organized array so return the number of operations, 2.

Example 2

Input:

items = [6, 5, 9, 7, 3]

Output:

3

Explanation: The array is not organized since, for example, items[2] mod 2 = items[3] mod 2. Here is the way to make items organized in 3 moves.

  1. Choose the 3rd index and divide it by 2; the new is [6, 5, 4, 7, 3].
  2. Choose the 5th index and divide it by 2; items = [6, 5, 4, 7, 1].
  3. Choose the 5th index and divide it by 2; items = [6, 5, 4, 7, 0] :)
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

The city of Hackerland organized a chess tournament for its citizens. There are n participants numbered 1 to n where the ith participant has potential denoted by potential[i]. The potential of each player is distinct. Initially, all players stand in a queue in order from the 1st to the nth player In each game, the first 2 participants of the queue compete and the participant with a higher potential wins the game. After each game, the winner remains at the beginning of the queue and plays with the next person from the queue and the losing player goes to the end of the queue. The game continues until a player wins k consecutive games. Given the potential of the participants and the deciding factor k, find the potential of the winning player. Function Description Complete the function getPotentialOfWinner in the editor below. getPotentialOfWinner has the following parameters:

  • int potential[n]: the potentials of participants
  • long k: the number of consecutive matches the winning participant must win Returns int: the potential of the winning player

Constraints

N/A

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

Implement an autocorrect function that returns all words which are anagrams of a search query. An anagram is any string that can be formed by rearranging the letters of another string. Given two arrays, words and queries of length n and q, respectively, for each query, return an array of strings that are anagrams of the query, sorted in alphabetical order. Function Description Complete the function getSearchResults in the editor with the following arguments:

  • string words[n]: the list of words to search
  • string queries[q]: the words to search for Returns string[q][]: the results for each search query Grateful beyond words to a wonderful old friend for your kind and generous help

Constraints

  • 1 ≤ n, q ≤ 5000
  • 1 ≤ length of words[i], length of queries[i] ≤ 100
  • It is guaranteed that each query word has at least one anag

Example 1

Input:

words = ["duel", "speed", "dule", "cars"]
queries = ["spede", "deul"]

Output:

[["speed"], ["duel", "dule"]]

Explanation: With words = ["duel", "speed", "dule", "cars"] and queries = ["spede", "deul"]:

  • For "spede", the only anagram is "speed"
  • For "deul", the anagrams are "duel" and "dule" Return [["speed"], ["duel", "dule"]].
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

A unique character is one that appears only once in a string. Given a string consisting of lowercase English letters only, return the index of the first occurrence of a unique character in the string using 1-based indexing. If the string does not contain any unique character, return -1. Function Description Complete the function getUniqueCharacter in the editor below. getUniqueCharacter has the following parameter(s):

  • string s: a string Returns int: either the 1-based index or -1

Constraints

  • 1 ≤ length of s ≤ 10⁵
  • The string s consists of lowercase English letters only.

Example 1

Input:

s = "statistics"

Output:

3

Explanation: The unique characters are [a, c] among which a occurs first. Using 1-based indexing, it is at index 3.

Example 2

Input:

s = "hackthegame"

Output:

3

Explanation: The unique characters are [c, k, t, g, m] out of which the character c occurs first, at index 3 :)

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

There are n types of items in a shop, where the number of items of type i is denoted by quantity[i]. The price of the items is determined dynamically, where the price of the m items is equal to the remaining number of items of type i. There are m customers in line to buy the items from the shop, and each customer will buy exactly one item of any type. The shopkeeper, being greedy, tries to sell the items in a way that maximizes revenue. Find the maximum amount the shopkeeper can earn by selling exactly one item to the customers optimally. Function Description Complete the function maximumAmount in the editor. maximumAmount has the following parameter:

  • int quantity[n]: the number of items of each type Returns long integer: the maximum revenue possible

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ m ≤ 10⁹
  • 1 ≤ quantity[i] ≤ 10⁹

Example 1

Input:

quantity = [10, 10, 8, 9, 1]
m = 6

Output:

55

Explanation: Given n = 5, quantity = [10, 80, 90, 30, 1], m = 6 One of the optimal ways to sell the items is as follows: The maximum possible revenue is 55.

Example 2

Input:

quantity = [8, 8, 8, 8]
m = 4

Output:

32

Explanation: Here, n = 4, quantity = [8, 8, 8, 8], m = 4 The optimal way is to sell one item of each type. The total amount earned is 8 + 8 + 8 + 8 = 32.

Example 3

Input:

quantity = [1, 2, 4]
m = 4

Output:

11

Explanation: One of the optimal ways to sell the items is as follows:

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

There is a computer network consisting of n servers, or nodes, numbered from 1 to n, and each node has a security value security_val[i]. A hacker must choose a starting node, start jumping through the network compromising servers along the way until reaching the end. From node x, the hacker can jump to node (x + K). If node (x + K) does not exist, the jump is out of the network and the hack ends. Initially, the hacker has access to 0 servers with 0 security value. The security value at each compromised node is added to the hacker's security value sum, and values may be negative. The task is to choose the starting node optimally such that the hacker compromises servers with the maximum possible security value sum.

Constraints

  • 1 ≤ n ≤ 10⁶
  • -10³ ≤ security_val[i] ≤ 10³
  • 1 ≤ k ≤ n

Example 1

Input:

security_val = [2, -3, 4, 6, 1]
k = 2

Output:

7

Explanation: The security value sum is security_val[1] + security_val[3] + security_val[5] = 2 + 4 + 1 = 7.

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

A customer has posted several web development projects on a freelancing platform, and various web developers have put in bids for these projects. Given the bid amounts and their corresponding projects, what is the minimum amount the customer can pay to have all projects completed? Note: If any project has no bids, return -1. Function Description Complete the function minCost in the editor. minCost has the following parameters: int numProjects: the total number of projects posted by the client (labeled from 0 to n-1) int project[n]: the projects that the freelancers bid on int bid[n]: the bid amounts posted by the freelancers Returns long: the minimum cost the client can spend to complete all projects, or -1 if any project has no bids.

Constraints

  • 1 ≤ numProjects, n ≤ 5 x 10⁵
  • 0 ≤ project[i]

Example 1

Input:

numProjects = 3
project = [2, 0, 1, 2]
bid = [8, 7, 6, 9]

Output:

21

Explanation: There is only one choice of who to hire for project 0, and it will cost 7 :D Likewise, there is only one choice for project 1, which will cost 6 :) For project 2, it is optimal to hire the first web developer, instead of the fourth, and doing so will cost 8 :P So the final answer is 7 + 6 + 8 = 21. If instead there were n = 4 projects, the answer would be -1 since there were no bids received on the fourth project :3

Example 2

Input:

numProjects = 2
project = [0, 1, 0, 1, 1]
bid = [4, 74, 47, 744, 7]

Output:

11

Explanation: The first web developer bid 4 units for project 0 The second web developer bid 74 units for project 1 The third web developer bid 47 units for projevt 0 so on so forth...

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

Given an integer array, reduce the array to a single element. In each operation, pick two indices i and j (where i ≠ j), and: append the value of a[i] + a[j] to the array delete a[i] and a[j] from the array The cost of each operation is a[i] + a[j]. Find the minimum possible cost to reduce the array. Function Description Complete the function minimizeCost in the editor. minimizeCost has the following parameter:

  • int arr[n]: an array of integers Returns int: the minimum cost of reducing the array

Constraints

  • 2 ≤ n ≤ 10⁵
  • 1 ≤ arr[i] ≤ 100

Example 1

Input:

arr = [25, 10, 20]

Output:

85

Explanation: Consider array [25,10,20].

  • Pick 10 and 20, cost = 10+20 = 30, array' = [25,30]
  • Pick 25 and 30, cost = 25+30 = 55, array" = [55] The cost is 30+55 = 85. This is the minimum possible cost.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Start with an initial string of zeros. Choose any digit to flip. When a digit is flipped, its value and those to the right switch state between 0 and 1. Given a target string of binary digits, determine the minimum number of flips required to achieve the target. Function Description Complete the function minimumFlips in the editor below. minimumFlips has the following parameter(s):

  • string target: a string of 0s and 1s to match Returns int: the minimum number of flips needed to obtain the target string

Constraints

  • 1 ≤ target.length ≤ 10⁵
  • target[i] ∈ {'0', '1'}

Example 1

Input:

target = "01011"

Output:

3

Explanation: Start with a string of 5 zeros, the same length as the target. Initial String → 00000 Flip the 3rd digit → 00111 Flip the 2nd digit → 01000 Flip the 4th digit → 01011 3 flips are required to reach the target. The return value is 3.

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

A shopkeeper in Koxland always each item in a shop a unique popularity rating. To order the items in decreasing popularity from left to right, the shopkeeper can swap any 2 items in one operation. Determine the minimum number of operations needed to reorder the items correctly. Function Description Complete the function minimumSwaps in the editor. minimumSwaps has the following parameters:

  • int popularity[n]: an array of integers that represents the popularity of each item Returns int: the minimum number of swaps to order the items properly

Constraints

  • 1 ≤ n ≤ 2 * 10⁵
  • 1 ≤ popularity[i] ≤ n

Example 1

Input:

popularity = [3, 4, 1, 2]

Output:

2

Explanation: First switch 3 and 4 to get popularity [4, 3, 1, 2]. Then switch 1 and 2 to get [4, 3, 2, 1]. The array is now reordered in 2 operations.

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

Count the number of substrings in a binary string that contain an equal number of 0s and 1s, where all 0s and 1s are grouped together. Duplicate substrings are counted in the total. A binary string consists only of 0s and 1s, and a substring is a contiguous group of characters within the string. Function Description Complete the function oneSubstringCount in the editor within the following parameter(s):

  • s: a binary string Returns int: the number of substrings that meet the criteria Endless gratitude to a dear old friend whose generosity in sharing the source made all the difference.

Example 1

Input:

s = "011001"

Output:

4

Explanation: The qualifying substrings are "01", "10", "1100", and "01", giving a total of 4. Note that "0110" has equal 0s and 1s but is not counted because the 0s and 1s are not grouped together.

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

给整数 startend,返回区间 [start, end] 内"所有十进制位都互不相同"的数的个数。

Example 1

Input:

start = 10
end = 13

Output:

3

Explanation: The valid numbers in the range 10-13 are 10, 12, and 13. The number 11 is not valid because it has repeating digits. Therefore, the count of numbers without repeating digits is 3.

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

Engineers have redesigned a keypad used by ambulance drivers in urban areas. In order to determine which key takes the longest time to press, the keypad is tested by a driver. Given the results of that test, determine which key takes the longest to press. Function Description Complete the function slowestKey in the editor below. slowestKey has the following parameter(s): int keyTimes[n][2]: the first column contains the encoded key pressed, the second

Constraints

n/a

Example 1

Input:

keyTimes = [[0, 2], [1, 5], [0, 9], [2, 15]]

Output:

c

Explanation: Elements in keyTimes[i][0] represent encoded characters in the range ascii[a-z] where a = 0, b = 1, ... z = 25. The second element, keyTimes[i][1] represents the time the key is pressed since the start of the test. The elements will be given in ascending time order. In the example, keys pressed, in order are 0[2/encoded] = abcat times 2, 5, 9, 15. From the start time, it took 2 - 0 = 2 to press the first key, 5 - 2 = 3 to press the second, and so on. The longest time it took to press a key was key 2, or 'c', at 15 - 9 = 6.

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

解锁全部 33 道题的解法

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

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

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