OAmaster
— / 32已做

Complete the implementation of an autocorrect function. Given a search query string, the function should return all words which are anagrams. Given 2 arrays, words[n], and queries[q], for each query, return an array of the strings that are anagrams, sorted alphabetically ascending. Note: An anagram is any string that can be formed by rearranging the letters of a string. Function Description Complete the function getSearchResults in the editor.

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 anagram in the word list

Example 1

Input:

n = 2
words = ["duel", "speed", "dule", "cars"]
queries = ["dpede", "deul"]

Output:

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

Explanation: The only anagram of "speed" is "spede". Both "duel" and "dule" are anagrams of "deul". Return [["speed"], ["duel", "dule"]].

解法

字符排序签名分组,每个 query 取签名查表并排序。O((n + q) · L log L)

def getSearchResults(words, queries):
    groups = {}
    for w in words:
        key = "".join(sorted(w))
        groups.setdefault(key, []).append(w)
    for v in groups.values(): v.sort()
    return [groups.get("".join(sorted(q)), []) for q in queries]
class Solution {
    String[][] getSearchResults(String[] words, String[] queries) {
        java.util.HashMap<String, java.util.List<String>> g = new java.util.HashMap<>();
        for (String w : words) {
            char[] ca = w.toCharArray(); java.util.Arrays.sort(ca);
            g.computeIfAbsent(new String(ca), k -> new java.util.ArrayList<>()).add(w);
        }
        for (var v : g.values()) java.util.Collections.sort(v);
        String[][] res = new String[queries.length][];
        for (int i = 0; i < queries.length; i++) {
            char[] ca = queries[i].toCharArray(); java.util.Arrays.sort(ca);
            var v = g.get(new String(ca));
            res[i] = v == null ? new String[0] : v.toArray(new String[0]);
        }
        return res;
    }
}
class Solution {
public:
    vector<vector<string>> getSearchResults(vector<string>& words, vector<string>& queries) {
        unordered_map<string, vector<string>> g;
        for (auto& w : words) { string k = w; sort(k.begin(), k.end()); g[k].push_back(w); }
        for (auto& [k, v] : g) sort(v.begin(), v.end());
        vector<vector<string>> res;
        for (auto& q : queries) {
            string k = q; sort(k.begin(), k.end());
            auto it = g.find(k);
            res.push_back(it == g.end() ? vector<string>() : it->second);
        }
        return res;
    }
};

Consider a string, S, that is a series of characters, each followed by its frequency as an integer. The string is not compressed correctly, so there may be multiple occurrences of the same character. A properly compressed string will consist of one instance of each character in alphabetical order followed by the total count of that character within the string. Function Description Complete the function betterCompression in the editor. betterCompression has the following parameter: S: a compressed string Return string: the properly compressed string

Constraints

1 'a' 1 ≤ frequency of each character in S ≤ 1000

Example 1

Input:

S = "a3c9b2c1"

Output:

"a3b2c10"

Explanation: The string 'a3c9b2c1' has two instances where 'c' is followed by a count: once with 9 occurrences, and again with 1. It should be compressed to 'a3b2c10'.

Example 2

Input:

S = "a12b56c1"

Output:

"a12b56c1"

Explanation: Noting is changed because character occurred only once and they are already sorted ascending.

解法

解析 S:交替读取 (字母, 数字串)。累加每个字母的总次数到 hashmap,按字母升序输出 字母 + 总次数O(|S|)

def betterCompression(S):
    cnt = {}
    i = 0
    while i < len(S):
        ch = S[i]; i += 1
        j = i
        while j < len(S) and S[j].isdigit(): j += 1
        cnt[ch] = cnt.get(ch, 0) + int(S[i:j])
        i = j
    return "".join(c + str(cnt[c]) for c in sorted(cnt))
class Solution {
    String betterCompression(String S) {
        java.util.TreeMap<Character, Integer> cnt = new java.util.TreeMap<>();
        int i = 0;
        while (i < S.length()) {
            char ch = S.charAt(i++);
            int j = i;
            while (j < S.length() && Character.isDigit(S.charAt(j))) j++;
            cnt.merge(ch, Integer.parseInt(S.substring(i, j)), Integer::sum);
            i = j;
        }
        StringBuilder sb = new StringBuilder();
        for (var e : cnt.entrySet()) sb.append(e.getKey()).append(e.getValue());
        return sb.toString();
    }
}
class Solution {
public:
    string betterCompression(string S) {
        map<char, int> cnt;
        int i = 0;
        while (i < (int)S.size()) {
            char ch = S[i++];
            int j = i;
            while (j < (int)S.size() && isdigit(S[j])) j++;
            cnt[ch] += stoi(S.substr(i, j - i));
            i = j;
        }
        string res;
        for (auto& [k, v] : cnt) res += k + to_string(v);
        return res;
    }
};

Two strings are said to be the same if they are of the same length and have the same character at each index. Backspacing in a string removes the previous character in the string. Given two strings containing lowercase English letters and the character # which represents a backspace key, determine if the two final strings are equal. Return 1 if they are equal or 0 if they are not. Note that backspacing an empty string results in an empty string. Function Description Complete the function compareStrings in the editor below. compareStrings has the following parameter(s):

  • string s1: the first string
  • string s2: the second string Returns int: either 0 or 1

Constraints

  • 1 5
  • Both s1 and s2 contain lowercase English letters and/or the char '#' only :)

Example 1

Input:

s1 = "axx#b#b#c"
s2 = "axbdf#c#c"

Output:

1

Explanation: In the first string, one 'x' and one 'b' are backspaced over. The first string becomes axbc. The second string also becomes axbc. The answer is 1.

解法

分别用栈处理两个串:遇 '#' 弹栈。比较最终栈。O(n)

def compareStrings(s1, s2):
    def proc(s):
        st = []
        for c in s:
            if c == '#':
                if st: st.pop()
            else:
                st.append(c)
        return "".join(st)
    return 1 if proc(s1) == proc(s2) else 0
class Solution {
    int compareStrings(String s1, String s2) {
        return proc(s1).equals(proc(s2)) ? 1 : 0;
    }
    String proc(String s) {
        StringBuilder st = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (c == '#') { if (st.length() > 0) st.setLength(st.length() - 1); }
            else st.append(c);
        }
        return st.toString();
    }
}
class Solution {
public:
    string proc(string s) {
        string st;
        for (char c : s) {
            if (c == '#') { if (!st.empty()) st.pop_back(); }
            else st += c;
        }
        return st;
    }
    int compareStrings(string s1, string s2) {
        return proc(s1) == proc(s2) ? 1 : 0;
    }
};

In data analysis, the eliminate algorithm determines the single final value to use for each data parameter. The eliminate algorithm works in the following way:

  • Data is acquired from multiple sources in order from least to most preferred, i.e if a parameter P is present in both source 1 and source 2, the parameter from the higher priority source, source 2, is used in the final parameter list, and any value from an earlier source is superseded.
  • As new parameters arrive, they are added to the list.
  • If a parameter P is present only in one of the sources, it is directly added to the final parameter list. Hence,
  • The result of performing the above operations until all parameters from source 1 and source 2 are exhausted is the result of Eliminate-algorithm(source 1, source 2).
  • Each time a new value for a parameter is encountered from a higher preferred site, the old data is superseded.
  • Assuming three sources S₁, S₂, S₃: Eliminate-algorithm(S₁, S₂, S₃) = Eliminate-algorithm (Eliminate-algorithm(S₁, S₂), S₃). Given a list of sources S₁, S₂...Sₙ, find the final parameter list given by Eliminate-algorithm(S₁, S₂...Sₙ). Maintain your results in the order a key was first encountered. For example, a rating parameter of buy, sell or hold from three sources in increasing order of preference: [buy, sell, hold], where buy is from S₁, immediately superseded by sell S₂, immediately superseded by hold S₃. The final rating is the only one that hasn't been superseded, so you use 'hold' as the final rating. Function Description Complete the function computeParameterValue in the editor. computeParameterValue has the following parameter(s):
  • String[][] sources: A 2-dimensional array of key: value pairs, each row is one source's data, sources presented from lowest to highest preference.

Constraints

  • 1 ≤ n < 100
  • 1 ≤ p < 1000

Example 1

Input:

sources = [["P1:a", "P3:b", "P5:x"], ["P1:b", "P2:q", "P5:x"]]

Output:

["b", "b", "x", "q"]

Explanation: Final parameter list:

  • P1 b (Source 2)
  • P3 b (Source 1)
  • P5 x (Source 2)
  • P2 q (Source 2)
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

A palindrome is a string that reads the same from the left and from the right. For example, mom and tacocat are palindromes, as are any single-character strings. Given a string, determine the number of its substrings that are palindromes. Function Description Complete the function countPalindromes in the editor. countPalindromes has the following parameter:

  • string s: the string to analyze Returns int: an integer that represents the number of palindromic substrings in the given string

Constraints

1 ≤ |s| ≤ 5 x 10³each character of s, s[i] ∈ ['a'-'z'].

Example 1

Input:

s = "tacocat"

Output:

10

Explanation: Palindromic substrings are ['t', 'a', 'c', 'o', 'c', 'a', 't', 'coc', 'acoca', 'tacocat']. There are 10 palindromic substrings.

Example 2

Input:

s = "aaa"

Output:

6

Explanation: There are 6 possible substrings of s: {'a', 'a', 'a', 'aa', 'aa', 'aaa'}. All of them are palindromes, so return 6.

Example 3

Input:

s = "abccba"

Output:

9

Explanation: There are 21 possible substrings of s, the following 9 of which are palindromes: {'a', 'a', 'b', 'b', 'c', 'c', 'cc', 'bccb', 'abccba'}.

Example 4

Input:

s = "daata"

Output:

7

Explanation: There are 15 possible substrings of s, the following 7 of which are palindromes: {'a', 'a', 'a', 'aa', 'ata', 'd', 't'}.

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

The owner of a construction company has a surplus of rods of arbitrary lengths. A local contractor offers to buy any of the surplus, as long as all the rods have the same exact integer length, referred to as saleLength. The number of sellable rods can be increased by cutting each rod zero or more times, but each cut has a cost denoted by costPerCut. After all cuts have been made, any leftover rods having a length other than saleLength must be discarded for no profit. The owner's total profit for the sale is calculated as: totalProfit = totalUniFormRods * saleLength * salePrice - totalCuts * costPerCut where totalUniformRods is the number of sellable rods, salePrice is the per unit length price that the contractor agrees to pay, and the totalCuts is the total number of times the rods needed to be cut. Function Description Complete the function maxProfit in the editor. maxProfit has the following parameter(s): costPerCut: cost to make a cut

  • salePrice : per unit length sales price
  • lengths[n]: integer rod lengths Returns
  • int: maximum possible profit

Constraints

  • 1 ≤ n ≤ 50
  • 1 ≤ lengths[i] ≤ 10⁴
  • 1 ≤ salePrice, costPerCut ≤ 100

Example 1

Input:

lengths = [30, 59, 110]
costPerCut = 1
salePrice = 10

Output:

1913

Explanation: Working through the first stanza, length = 30, it is the same length as the first rod, so no cuts are required and there is 1 piece. For the second rod, cut and discard the excess 29 unit rod. No more cuts are necessary and another 1 piece is left to sell. Cut 20 units off the 110 unit rod to discard leaving 90 units, then make two more cuts to have 3 more pieces to sell. Finally sell 5 totalUniformRods, costPerCut = 1 per cut, or 4. Total revenue = 1500 - 4 = 1496. The maximum revenue among these tests is obtained at length 5 for 1913.

Example 2

Input:

lengths = [26, 103, 59]
costPerCut = 100
salePrice = 10

Output:

1230

Explanation: Since costPerCut = 100, cuts are expensive and must be minimal. The optimal rod length for maximizing profit is 51, and the rods are cut as shown: lengths[0] = 26: Discard this rod entirely. lengths[1] = 103: Cut off a piece of length 1 and discard it, resulting in a rod of length 102. Then, cut this rod into 2 pieces of length 51. lengths[2] = 59: Cut off a piece of length 8 and discard it, resulting in a rod of length 51. After performing totalCuts = (0) + (1 + 1) + (1) = 3 cuts, there are totalUniformRods = 0 + 2 + 1 = 3 pieces of length saleLength = 51 that can be sold at salePrice = 10 each. This yields a total profit of salePrice * totalUniformRods * saleLength - totalCuts * costPerCut = 10 * 3 * 51 - 3 * 100 = 1230.

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

Many simple encoding methods have been devised over the years. A common method is the ASCII character set used to display characters on the screen. Each character is given a numeric value which can be interpreted by the computer. To decode the string, first reverse the string of digits, then successively pick valid values from the string and convert them to their ASCII equivalents. Some of the values will have two digits, and others three. Use the ranges of valid values when decoding the string of digits. The value range for A through Z is 65 through 90. The value range from a through z is 97 through 122. The value of the space character is 32. Given a string, decode it following the steps mentioned above. Function Description Complete the function decode. decode has the following parameter(s): string encode: an encoded string Return string: the original decoded string decode.

Constraints

  • 1 ≤ |s| ≤ 10⁵
  • s[i]is an ascii character in the range [A-Z a-z] or a space character
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Build a computer simulation of a mobile robot. The robot moves on an infinite plane, starting from position (0, 0). Its movements are described by a command string consisting of one or more of the following three letters:

  • G instructs the robot to move forward one step.
  • L instructs the robot to turn left in place.
  • R instructs the robot to turn right in place. The robot performs the instructions in a command sequence in an infinite loop. Determine whether there exists some circle such that the robot always moves within the circle. Consider the commands R and G executed infinitely. A diagram of the robot's movement looks like: The robot will never leave the circle. Function Description Complete the function doesCircleExist in the editor below. The function must return an array of n strings either YES or NO based on whether the robot is bound within a circle or not, in order of test results. doesCircleExist has the following parameter(s): commands[commands[0],...commands[n-1]]: An array of n commands[i] where each represents a list of commands to test.

Constraints

  • 1 ≤ |commands[i]| ≤ 2500
  • 1 ≤ n ≤ 10
  • Each command consists of G, L, and R only.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Encryption is the process of converting information algorithmically so that a valid recipient can read the information before it is no longer a valuable secret. This is its validity period. An attacker has limited processing power and can only test a certain number of keys per second. This is the instruction count. The size of the universe of keys divided by the instruction count gives the average time to find a message key. To achieve a balance between the processing power for encryption/ decryption and the strength of the encryption, the validity period of the message must be taken into consideration. Given the number of keys, a hijacker can test per second, determine if the encrypted information should remain confidential throughout its validity period. Each test will return two items of information as integers: Can a hijacker crack the code within the period? (1 if true, 0 if false) The strength of the encryption, that is, the number of keys that must be tested to break the encryption. The strength of the encryption is determined as follows: Keys is a list of positive integers, keys[i], that act as keys. The degree of divisibility of an element is the number of elements in the set keys that are greater than 1 and are divisors of the element, i.e element modulo divisor = 0. The element m that has the maximum number of divisors (or degree of divisibility) in keys is used to determine the strength of the encryption. The strength of the encryption is defined as (the degree of divisibility of m) * 10⁵ Function Description Complete the function encryptionValidity. encryptionValidity has the following parameter(s): int instructionCount: the number of keys the hijacker can test per second int validityPeriod: the number of seconds the message must be protected. int keys[n]: the keys for encryption/decryption

Constraints

  • 1 ≤ instructionCount, validityPeriod ≤ 10⁸
  • 1 ≤ 1 ≤ n ≤ 10⁵
  • 1 ≤ 1≤ keys[i] ≤ 10⁵

Example 1

Input:

instructionCount = 1000
validityPeriod = 10000
keys = [2, 4, 8, 2]

Output:

[1, 400000]

Explanation: The element m that has the maximum number of divisors is 8 ad its degree of divisibility is 4. The encryption strength is 4 * 10⁵ = 400,000. The hijacker can perform instructionCount = 1,000 calculations per second. During the total validityPeriod = 10,000 seconds, the hijacker can test 1000 * 1000 = 1000000 = 10⁷ keys. Thus, there is sufficient time for the key to be determined and the message decrypted before its validity expires. The first value in the return array is 1 because the message can be decrypted. The return array is [1, 400000] because the hijacker can decrypt the message in time, and the strength of the encryption is 400000.

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

John is teaching his son Rob English alphabet and number counting. He reperesents 'a' as the 1^st character, 'b' as the 2^nd character up to 'z' as the 26^th character. John says 'kite' can be representd as '119205'. The 11^th character is 'k', 9^th character is 'i', 20^th character is 't' and 5^th character is 'e'. Rob being smarter than him, says '119205' can also mean 'aaite' (1)(1)(9)(20)(5), 'aste'(1)(19)(20)(5), etc. Now being enthusiastic about it, John wants to know given a string os length n containing digits from 0 to 9, how many such words are possible. Input Format You are given a string S containing characters from 0-9. You have to find how many such words are possible for that given number sequence, Output Format A single integer returning the number of words. If there are no possible combinations output will be 0.

Example 1

Input:

S = "2112"

Output:

5

Explanation: 2112 can be represented as: (2)(1)(1)(2) is represented as baab (2)(1)(12) is represented as bal (2)(11)(2) is represented as bkb (21)(1)(2) is represented as uab (21)(12) is represented as ul Therefore, the answer in this case is 5 :)

Example 2

Input:

S = "2101"

Output:

1

Explanation: (2)(10)(1) is the only solution. Heads up Do not consider (01) to be 'a' as this can be chained to (001), (0001).

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

You are given an array of integers codeSequence of length n and an integer maxValue. A locking system allows you to modify any number in the array to any integer less than or equal to maxValue at a cost of 1 per change. Two numbers are co-prime if their greatest common divisor (GCD) is 1. To unlock the repository, you need to select a number from the array that is co-prime with all other numbers in the array. The lock's code is calculated as the maximum possible value of: selected number - total modification cost Your task is to determine the lock code by selecting an optimal number from the array after modifications that is co-prime with all other numbers in the array. Function Description Complete the function decryptCodeLock in the editor with the following parameters:

  • int codeSequence[n]: the array presented by the code lock
  • int maxValue: the maximum possible value for any element in the array Returns int: the lock code

Constraints

  • 1 ≤ n ≤ 10³
  • 1 ≤ maxValue ≤ 10⁹
  • 1 ≤ codeSequence[i] ≤ maxValue

Example 1

Input:

codeSequence = [3, 2, 4]
maxValue = 6

Output:

4

Explanation: Optimally:

  • Change the element at the third position to 5 at the cost of 1 unit: codeSequence' = [3, 2, 5].
  • Choose the element 5 since it is co-prime with both 2 and 3.
  • Calculate lock code = selected number - cost = 5 - 1 = 4. Return 4 as the answer.

Example 2

Input:

codeSequence = [1, 2, 3]
maxValue = 6

Output:

4

Explanation: Optimally, change the second and third elements to 5 and 6 at a cost of 2 units, resulting in [1, 5, 6]. The number 6 is coprime with both 1 and 5. The lock's code is 6 - 2 (cost) = 4.

Example 3

Input:

codeSequence = [2, 4, 6, 8]
maxValue = 8

Output:

6

Explanation: Optimally, change the third element to 7 at a cost of 1 unit, resulting in [2, 4, 7, 8]. The number 7 is coprime with 2, 4, and 8. The lock's code is 7 - 1 (cost) = 6.

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

Encodes or decodes a message using a shared numeric key. Input

  • Operation:
  • 1 = Encode
  • 2 = Decode
  • Message (string)
  • Key (positive integer) Encoding (Operation 1) Duplicates each character based on the corresponding digit in the key. Example: Message: Open, Key: 123 → Output: Oppeen Decoding (Operation 2) Compresses repeated characters based on digits in the key. Example: Message: Oppeen, Key: 123 → Output: Open Rules Apply digits in key cyclically or until message ends. Remaining characters (if key ends first) are left unchanged. Return -1 for invalid input or mismatched patterns during decoding.

Example 1

Input:

operation = 1
message = "Open"
key = 123

Output:

"Oppeen"

Explanation: ~~

Example 2

Input:

operation = 2
message = "Oppeen"
key = 123

Output:

"Open"

Explanation:

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

Given n number of kids, t toys and random numbe

Example 1

Input:

N = 5
T = 2
D = 1

Output:

2

Explanation: As we will start from 1 and kid getting last toy is 2.

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

In a tranquil village school, there are two students named Ramu and Sonu, each possessing a collection of N distinct chalks. Each student's chalks are of different lengths, represented by N positive integers. Ramu has arranged his collection of N chalks in a specific order based on their lengths. Sonu is eager to organize his own N chalks in a way that mimics Ramu's arrangement in terms of length changes i.e. if in Ramu's arrangement the k^th chalk is bigger than the k+1^th chalk, in Sonu's arrangement also the k^th chalk will be bigger than the k+1^th arrangement, alternately if it is smaller in Ramu's arrangement, then it will be smaller in Sonu's as well. Sonu was busy arranging his chalks, when his teacher told him to also maximize the "niceness" of his arrangement. Here, the "niceness" of the arrangement is defined as the sum of the absolute length differences between all adjacent chalks in the arrangement. Write a program to assist Sonu in achieving both the objectives: first, to mimic Ramu's length variation order, and second, to maximize the overall niceness of the arrangement. Read the input from STDIN and print the output to STDOUT. Do not write arbitrary strings anywhere in the program, as these contribute to the standard output, and test cases will fail. Objective Find the maximum achievable niceness resulting from the arrangement of Sonu's chalk collection to mimic Ramu's chalk arrangement.

Constraints

  • 2 ≤ N ≤ 10^5
  • 1 ≤ ramu[i], sonu[i] ≤ 10^9
  • ramusonu 内部元素各自互不相同
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given a string representing a sequence of digits, find the number of different words that can be formed by interpreting the digits as indices in the alphabet where '1' corresponds to 'a', '2' to 'b', and so on, up to '26' for 'z'. A valid word is formed by splitting the string into one or two-digit numbers and then mapping those numbers to their corresponding letters. The number '0' does not correspond to any letter, and numbers greater than '26' do not correspond to any letter. Function Description Complete the function numDifferentWords in the editor. numDifferentWords has the following parameter:

  • String s: the string representing the sequence of digits Returns int: the number of different words that can be formed

Example 1

Input:

s = "1192"

Output:

3

Explanation: The following different words can be formed from the string "1192":

  • 1,1,9,2 - aaib
  • 11,9,2 - kib
  • 1,19,2 - asb Therefore, the answer is 3.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

At a birthday party, N kids (IDs from 1 to N) sit in a circle. The host has T toys to distribute, starting from kid with ID D and giving one toy at a time in ascending order. After reaching kid N, the count continues from kid 1. Input Three integers:

  • N: Number of kids
  • T: Number of toys
  • D: Starting kid's ID Output Print the ID of the kid who receives the damaged (last) toy.

Example 1

Input:

N = 5
T = 2
D = 1

Output:

2

Explanation: :)

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

Process scheduling algorithms are used by a CPU to optimally schedule the running processes. A core can execute one process at a time, but a CPU may have multiple cores. There are n processes where the ith process starts its execution at start[i] and ends at end[i], both inclusive. Find the minimum number of cores required to execute the processes. Function Description Complete the function getMinCores in the editor below. getMinCores takes the following arguments:

  • int start[n]: the start times of processes
  • int end[n]: the end times of processes Returns int: the minimum number of cores required Constraints
  • 1 ≤ n ≤ 10⁵
  • 1 ≤ start[i]end[i] ≤ 10⁹
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

There is a maze in HackerPlay where children play for recreation. The maze is represented as an n x m grid of cells, where each cell is either empty (denoted by 0), or contains an obstacle (denoted by 1). HackerMan is currently standing at cell (0, 0), and wishes to reach the cell (n - 1, m - 1). For a jump parameter denoted by k, in one move, HackerMan can move to any of the following cells:

  • (i + k, j) where 1 ≤ k ≤ n provided cell (i + k, j) lies in the maze and there are no cells containing obstacles in the range (i + 1, j) to (i + k, j).
  • (i, j + k) where 1 ≤ k ≤ m provided cell (i, j + k) lies in the maze and there are no cells containing obstacles in the range (i, j + 1) to (i, j + k).
  • (i - k, j) where 1 ≤ k ≤ n provided cell (i - k, j) lies in the maze and there are no cells containing obstacles in the range (i - 1, j) to (i - k, j).
  • (i, j - k) where 1 ≤ k ≤ m provided cell (i, j - k) lies in the maze and there are no cells containing obstacles in the range (i, j - 1) to (i, j - k). Determine the minimum number of moves in which HackerMan can reach the cell (n - 1, m - 1) starting from (0, 0), or -1 if it is impossible to reach that cell. Function Description Complete the function getMinimumMoves in the editor. getMinimumMoves has the following parameters:
  • int maze[n][m]: the maze in HackerPlay where HackerMan is standing
  • int k: the maximum distance HackerMan can traverse in one move Returns int: the minimum number of moves in which HackerMan can reach the destination cell (n - 1, m - 1)

Constraints

  • 1 ≤ n, m ≤ 100
  • 1 ≤ k ≤ 100
  • Each cell of the grid contains values either 0 or 1.

Example 1

Input:

maze = [[0, 1], [1, 0]]
k = 2

Output:

2

Explanation: The maze looks like this. [[0, 0], [1, 0]] The following sequence of moves can be performed: (0, 0) to (0, 1) to (1, 1). Hence, HackerMan can reach the end in 2 moves, which is minimum possible. The answer is 2.

Example 2

Input:

maze = [[0, 0, 0], [1, 0, 0], [1, 0, 0]]
k = 5

Output:

2

Explanation: The maze can be represented as: [[0, 0, 0], [1, 0, 0], [1, 0, 0]] The following sequence of moves can be performed: (0, 0) to (0, 2) to (1, 2).

Example 3

Input:

maze = [[0, 1, 0], [1, 0, 0], [1, 0, 0]]
k = 5

Output:

-1

Explanation: The maze can be represented as: [[0, 1, 0], [1, 1, 0], [1, 0, 0]] HackerMan is blocked and cannot move from the cell (0, 0).

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

While analyzing data, you are working with an array data containing n positive integers, each representing a dataset values. To derive new features for data analysis, you can perform the following operations:

  1. Select a pair of indices (i,j) (0-based) such that 0 ≤ i 2. Compute the absolute difference |data[i] - data[j]|`.
  2. Append this value to the end of the array data, increasing its length by 1. The objective is to minimize the smallest value present in data after performing exactly maxOperations operations. Write a program to compute the minimum possible value of the smallest element in data after the given operations. Function Description Complete the function getMinimumValue in the editor with the following parameters:
  • int data[]: the dataset
  • int maxOperations: the number of operations to be performed Returns int: the smallest possible value of the minimum element in data after exactly maxOperations operations. Constraints
  • 2 ≤ n ≤ 2*10³
  • 1 ≤ data[i] ≤ 10⁹
  • 1 ≤ maxOperations ≤ 10⁹

Constraints

See the very last portion of the problem statement above

Example 1

Input:

data = [42, 47, 50, 54, 62, 79]
maxOperations = 2

Output:

3

Explanation: The underlined values are selected for the operation. An optimal sequence of operation is as follows: The smallest possible value of the minimum element is 3.

Example 2

Input:

data = [4, 2, 5, 9, 3]
maxOperations = 1

Output:

1

Explanation: The underlined values are selected for the operation. An optimal sequence of operation is as follows: The smallest possible value of the minimum element is 1.

Example 3

Input:

data = [5, 18, 3, 12, 11]
maxOperations = 2

Output:

1

Explanation: The smallest possible value of the minimum element is 1 :)

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

You are given a logging system with a circular buffer that can hold up to n logs. Each log has a unique timestamp logTimestamp[i] (in milliseconds) and a tag logTag[i]. When a new log arrives, the system: renames all logs sharing the same tag as the new log, but only if they fall within a specific time window (transmissionWindow). If the buffer is full, it removes the oldest log to make space for the new one. Implement a function that finds the total number of logs transmitted throughout the process as logs arrive, considering the circular buffer's capacity and the time window for transmission. Function Description Complete the function getNumberTransmittedLogs in the editor getNumberTransmittedLogs takes the following parameters:

  • int logTimestamp[]: the recording times of logs in milliseconds
  • string logTag[]: the tags of logs
  • int bufferCapacity: the capacity of the circular buffer
  • int transmissionWindow: the time range (in milliseconds) within which logs sharing the same tag as the arriving log are transmitted Returns int: the number of logs transmitted during the process A SUPER huge thank you to our incredible friend for everything they've contributed!

Example 1

Input:

logTimestamp = [1000, 2000, 3000, 4001]
logTag = ["error", "warning", "error", "warning"]
bufferCapacity = 3
transmissionWindow = 2000

Output:

5

Explanation: The logs received are as follows:

  • Log 1: Timestamp = 1000 ms, Tag = "error"
  • Log 2: Timestamp = 2000 ms, Tag = "warning"
  • Log 3: Timestamp = 3000 ms, Tag = "error"
  • Log 4: Timestamp = 4001 ms, Tag = "warning" Condition of Buffer and logs transmitted during the process: The total number of logs transmitted during the process is 5, thus, the function should return 5.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

A subarray of array a is defined as a contiguous block of a's elements having a length that is less than or equal to the length of the array. For example, the subarrays of array a = [1, 2, 3] are [1], [2], [3], [1, 2], [2, 3], and [1, 2, 3]. Given an integer, k = 3, the subarrays having elements that sum to a number ≤ k are [1], [2], and [1, 2]. The longest of these subarrays is [1, 2], which has a length of 2. Given an array, a, determine its longest subarray that sums to less than or equal to a given value k. Function Description Complete the function maxLength in the editor below. The function must return an integer that represents the length of the longest subarray of a that sums to a number ≤ k. maxLength has the following parameter(s):

  • a[a[0],...a[n-1]]: an array of integers
  • k: an integer

Constraints

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

Example 1

Input:

a = [1, 2, 3]
k = 4

Output:

2

Explanation: The subarrays having elements that sum to a number ≤ 4 are [1], [2], and [1, 2]. The longest of these subarrays is [1, 2], which has a length of 2.

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

A product manager has to organize n meetings with different people. Meeting with each person results in an increase or decrease in the effectiveness index of the manager. The manager wants to organize the meetings such that the index remains positive for as many meetings as possible. Find the maximum number of meetings for which the effectiveness index is positive. The index at the beginning is 0. Note: After the meetings begin, the index must remain above 0 to be positive. Function Description Complete the function maxMeetings in the editor. maxMeetings has the following parameter:

  • int effectiveness[n]: the increase or decrease effectiveness for each meeting. Returns int: the maximum possible number of meetings while maintaining a positive index

Constraints

  • 1 ≤ n ≤ 10⁵
  • -10⁹ ≤ effectiveness[i] ≤ 10⁹

Example 1

Input:

effectiveness = [1, -20, 3, -2]

Output:

3

Explanation: One optimal meeting order is [3, -2, 1, -20]. The index is positive for the first three meetings, after which it is 3 - 2 + 1 = 1. So, the answer is 3. There is no way to have 4 meetings with a positive index.

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

A subsequence of an array is formed by removing zero or more elements from an array without changing the order of the remaining elements. In a valid subsequence, each pair of adjacent elements of the subsequence has bitwise XOR equal to k. Note that any subsequence of length 1 is valid regardless of the value of k, because there is no pair of adjacent elements in such a subsequence. Given an array of integers and integer k, determine the length of the longest valid subsequence in the array. Function Description Complete the function maxSubsequenceLength in the editor below. The function must return the length of the longest valid subsequence of the array, given parameter k. maxSubsequenceLength has the following parameter(s):

  • int n: the size of arr
  • int arr[n]: an array of integers
  • int k: an integer Constraints
  • 1 ≤ n ≤ 10⁵
  • 0 ≤ arr[i] ≤ 10⁶
  • 0 ≤ k ≤ 10⁶ Input Formatting In the first line, there is a single integer, n, the number of elements in arr. Each of the following n lines contains a single integer, arr[i]. In the last line, there is a single integer, k, the value the bitwise XOR of adjacent elements must equal for the subsequence to be valid.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 0 ≤ arr[i] ≤ 10⁶
  • 0 ≤ k ≤ 10⁶
  • ~ constriants added on 03-13-2025 :)
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

In this challenge, determine the minimum number of chairs to be purchased to accommodate all workers in a new business workroom. There is no chair at the beginning. There will be a string array of simulations. Each simulation is described by a combination of four characters: C, R, U, and L

  • C - A new employee arrives in the workroom. If there is a chair available, the employee takes it. Otherwise, a new one is purchased.
  • R - An employee goes to a meeting room, freeing up a chair.
  • U - An employee arrives from a meeting room. If there is a chair available, the employee takes it. Otherwise, a new one is purchased.
  • L - An employee leaves the workroom, freeing up a chair. Function Description Complete the minChair function. minChair has the following parameter(s):
  • string simulation[n]: an array of strings representing discrete simulations to process. Return int[n]: an array of integers denoting the minimal number of chairs required for each simulation.

Constraints

  • 1 ≤ n ≤ 100
  • 1 ≤ length of each simulation[i] ≤ 10000
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Consider an array of integers and a non-zero positive starting value x. A running sum is calculated by adding each element of the array to x consecutively. Determine the minimum value of x such that the running sum is at least 1 after every iteration. Function Description Complete the function minStart in the editor. minStart has the following parameter(s):

  • int arr[n]: an array of integers to sum Returns long: the minimum initial value

Constraints

  • 1 ≤ n ≤ 10⁵
  • -10⁶ ≤ arr[i] ≤ 10⁶

Example 1

Input:

arr = [-5, 4, -2, 3, 1, -1, -6, -1, 0, 5]

Output:

8

Explanation: Any initial value less than 8 will fail. For example, the running sums for an initial value of 7 is [2, 6, 4, 7, 8, 7, 1, 0, 0, 5].

Example 2

Input:

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

Output:

6

Explanation: Starting with a value of 6 gives the following sums: 6 + -5 = 1 → 1 + 4 = 5 → 5 + -2 = 3 → 3 + 3 = 6 → 6 + 1 = 7. Any initial value less than 6 will fail at the first element.

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

Consider a pair of integers, (a, b). The following operations can be performed on (a, b) in any order, zero or more times.

  • (a, b) → (a + b, b)
  • (a, b) → (a, a + b) Return a string that denotes whether or not (a, b) can be converted to (c, d) by performing the operation zero or more times. Function Description Complete the function isPossible in the editor. isPossible has the following parameter(s):
  • int a: first value in (a, b)
  • int b: second value in (a, b)
  • int c: first value in (c, d)
  • int d: second value in (c, d) Returns string: "Yes" if possible, otherwise "No"

Constraints

1 ≤ a, b, c, d ≤ 1000

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

Starting with an empty set of integers named elements, perform the following query operations:

  • The command push x inserts the value of x into elements.
  • The command pop x removes the value of x from elements. The integers in elements need to be ordered in such a way that after each operation is performed, the product of the maximum and minimum values in the set can be easily calculated. Function Description Complete the function maxMin in the editor below. maxMin has the following parameter(s):
  • s[n]: an array of operations strings
  • int x[n]: an array of x where x[i] goes with operations[i]. Returns int[n]: an array of long integers that denote the product of the maximum and minimum of elements after each query

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ x[i] ≤ 10⁹
  • It is guaranteed that each operations[i] is either push or pop.
  • It is guaranteed that any value popped will exist in the array.

Example 1

Input:

operations = ["push", "push", "push", "pop"]
x = [1, 2, 3, 1]

Output:

[1, 2, 3, 6]

Explanation: Visualize elements as an empty multiset, elements = {}, and refer to the return array as products. The sequence of operations occurs as follows:

  • push 1 → elements = {1}, so the minimum = 1 and the maximum = 1. Then store the product as products[0] = 1 × 1 = 1.
  • push 2 → elements = {1, 2}, so the minimum = 1 and the maximum = 2. Then store the product as products[1] = 1 × 2 = 2.
  • push 3 → elements = {1, 2, 3}, so the minimum = 1 and the maximum = 3. Then store the product as products[2] = 1 × 3 = 3.
  • pop 1 → elements = {2, 3}, so the minimum = 2 and the maximum = 3. Then store the product as products[3] = 2 × 3 = 6. Return products = [1, 2, 3, 6]
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

A is an array of integers described as {A[0], A[1], A[2], A[3],..., A[n-1]}. Perform the following calculations on the elements of A: (R_even = (((A[0] × A[2]) + A[4]) × A[6]) + A[8]) × ...) % 2 ) (R_odd = (((A[1] × A[3]) + A[5]) × A[7]) + A[9]) × ...) % 2 ) Notice that zero-indexing is used to calculate R_even and R_odd and they are always modulo 2. You can then use R_even and R_odd to determine if A is odd, even, or neutral using the criterion below: If R_odd > R_even, then A is ODD.

  • If R_even > R_odd, then A is EVEN.
  • If R_odd = R_even, then A is NEUTRAL. For example, given the array A = [12,3,5,7,13,12], calculations are:
  • R_even = (A[0] * A[2] + A[4]) % 2 = (12 * 5 + 13) % 2 = 73 % 2 = 1
  • R_odd = (A[1] * A[3] + A[5]) % 2 = (3 * 7 +12) % 2 = 33 % 2 = 1 Since both are 1, the answer is NEUTRAL.

Constraints

No constraints are mentioned for input.

Example 1

Input:

A = [12, 3, 5, 7, 13, 12]

Output:

"NEUTRAL"

Explanation: Perform the operations as follows: R_even = (12 * 5 + 13) % 2 = 73 % 2 = 1 R_odd = (3 * 7 + 12) % 2 = 33 % 2 = 1 Both R_even and R_odd are equal, hence A is NEUTRAL.

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

A triangle formed by the three points a(x1, y1), b(x2, y2) and c(x3, y3) is a non-degenerate triangle if the following rules are respected (|ab| is the length of the line between points a and b):

  • |ab| + |bc| > |ac|
  • |bc| + |ac| > |ab|
  • |ab| + |ac| > |bc| A point belongs to a triangle if it lies somewhere on or inside the triangle. Given two points p = (xp, yp) and q = (xq, yq), return the correct scenario number:
  • 0: If the triangle abc does not form a valid non-degenerate triangle.
  • 1: If point p belongs to the triangle but point q does not.
  • 2: If point q belongs to the triangle but point p does not.
  • 3: If both points p and q belong to the triangle.
  • 4: If neither point p nor point q belong to the triangle. Function Description Complete the function pointsBelong in the editor below. pointsBelong has the following parameter(s):
  • int x1, y1, x2, y2, x3, y3: integer coordinates of the three points that may create a valid triangle
  • int xp, yp, xq, yq: integer coordinates of the two points p and q Returns int: an integer value that represents the scenario

Constraints

0 ≤ x1, y1, x2, y2, x3, y3, xp, yp, xq, yq ≤ 2000

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

On a web form, users are asked to enter dates which come in as strings. Before storing them to the database, they need to be converted to a standard safe format. Write a function to convert the dates as described. Given a date string in the format Day Month Year, where:

    • Day is a string in the form "1st", "2nd", "3rd", "21st", "22nd", "23rd", "31st" and all other are the number + "th", eg: "4th" or "12th".
  • Month is the first three letters of the English language months, like "jan" for January through "Dec" for December.
  • Year is 4 digits ranging from 1900 to 2100. Convert the date string "Day Month Year" to the date string "YYYY-MM-DD" in the format "4 digit year - 2 digit month - 2 digit day". Function Description Complete the function preprocessDate. preprocessDate has the following parameter(s):
  • string dates[n]: an array of date strings in the format Day Month Year Returns string[n]: array of converted date strings

Constraints

  • the values of Day, Month, Year are restricted to the value ranges specified above.
  • The given

Example 1

Input:

dates = ["1st Mar 1974", "22nd Jan 2013", "7th Apr 1904"]

Output:

["1974-03-01", "2013-01-22", "1904-04-07"]

Explanation:

  • 1st Mar 1974 is converted to 1974-03-01.
  • 22nd Jan 2013 is converted to 2013-01-22.
  • 7th Apr 1904 is converted to 1904-04-07.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

A number of bids are being taken for a project. Determine the number of distinct pairs of project costs where their absolute difference is some target value. Two pairs are distinct if they differ in at least one value. Function Description Complete the function countPairs in the editor. countPairs has the following parameter(s): int projectCosts[n]: array of integers int target: the target difference Returns int: the number of distinct pairs in projectCosts with an absolute difference of target

Constraints

  • 5 < n ≤ 2 * 10⁵
  • 0 < projectCosts[i] ≤ 2 * 10⁹
  • Each projectCosts[i] is distinct, i.e. unique within projectCosts
  • 1 ≤ target≤ 10⁹

Example 1

Input:

n = 5
projectCosts = [1, 5, 3, 4, 2]
target = 2

Output:

3

Explanation: Count the number of pairs in projectCosts whose difference is target = 2. The following three pairs meet the criterion: (1, 3), (5, 3), and (4, 2).

Example 2

Input:

n = 3
projectCosts = [1, 3, 5]
target = 2

Output:

2

Explanation: There are 2 pairs [1, 3], [3, 5] that have the target difference target = 2, therefore a value of 2 is returned.

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

A compliance system monitors incoming and outbound calls. It sends an alert whenever the average number of calls over a trailing number of minutes exceeds a threshold. If the number of trailing minutes to consider, precedingMinutes = 5, at time T, take the average the call volumes for times T-5(T-1), T-5(2)...T-5(5). No alerts are sent until at least T = 3 because there are not enough values to consider. When T = 3, the average calls = (2 + 2 + 2)/3 = 2. Additionally, average calls from T = 3 to T = 8 are 2, 2, 3, 4, 5, and 6. A total of two alerts are sent during the last two periods. Given the data as described, determine the number of alerts sent by the end of the timeframe. Function Description Complete the function numberOfAlerts in the editor. numberOfAlerts has the following parameters:

    1. int precedingMinutes: the trailing number of minutes to consider
    1. int alertThreshold: the maximum number of calls allowed before triggering an alert
    1. int numCalls[n]: numCalls[i] represents the number of calls made during the ith minute Returns int: the number of alerts sent over the timeframe

Constraints

  • 1 ≤ precedingMinutes ≤ n
  • 1 ≤ alertThreshold ≤ 10⁵
  • `1
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁
Pro 会员

解锁全部 29 道题的解法

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

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

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