OAmaster
— / 33已做

When given a number N, for each integer i in the range from 1 to N inclusive, print one value per line as follows:

  • If i is a multiple of both 3 and 5, print FizzBuzz.
  • If i is a multiple of 3 but not 5, print Fizz.
  • If i is a multiple of 5 but not 3, print Buzz.
  • Otherwise, print the value of i.

Constraints

0 < N ≤ 2 × 10⁶.

解法

线性扫描,用 by3 / by5 两个布尔标记。输出用 StringBuilder 或预分配字符串缓冲,避免大 N 下的二次拼接。复杂度 O(N)

import sys

def fizz_buzz(n: int) -> str:
    out = []
    for i in range(1, n + 1):
        by3, by5 = i % 3 == 0, i % 5 == 0
        if by3 and by5: out.append("FizzBuzz")
        elif by3:       out.append("Fizz")
        elif by5:       out.append("Buzz")
        else:           out.append(str(i))
    return '\n'.join(out)

if __name__ == "__main__":
    n = int(sys.stdin.readline())
    sys.stdout.write(fizz_buzz(n))
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= n; i++) {
            boolean by3 = i % 3 == 0, by5 = i % 5 == 0;
            if (by3 && by5)      sb.append("FizzBuzz");
            else if (by3)        sb.append("Fizz");
            else if (by5)        sb.append("Buzz");
            else                 sb.append(i);
            sb.append('\n');
        }
        System.out.print(sb);
    }
}
#include <bits/stdc++.h>
using namespace std;

int main() {
 ios::sync_with_stdio(false);
 int n; cin >> n;
 string out;
 out.reserve(n * 4);
 for (int i = 1; i <= n; i++) {
 bool by3 = i % 3 == 0, by5 = i % 5 == 0;
 if (by3 && by5) out += "FizzBuzz";
 else if (by3) out += "Fizz";
 else if (by5) out += "Buzz";
 else out += to_string(i);
 out += '\n';
 }
 cout << out;
}

There is a set of N jars containing chocolates. Some of them may be empty. Determine the maximum number of chocolates Andrew can pick from the jars given that he cannot pick from jars next to each other.

Input: first line N, second line N space-separated integers (chocolates per jar). Output: max chocolates pickable. Constraints

1 ≤ N ≤ 1000.

解法

经典打家劫舍 DP:dp[i] = max(dp[i-1], dp[i-2] + jars[i])。滚动两个变量即可。时间 O(N),空间 O(1)

def tallest_chocolate(jars: list[int]) -> int:
    prev2 = prev1 = 0
    for x in jars:
        prev2, prev1 = prev1, max(prev1, prev2 + x)
    return prev1
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int prev2 = 0, prev1 = 0;
        for (int i = 0; i < n; i++) {
            int x = sc.nextInt();
            int cur = Math.max(prev1, prev2 + x);
            prev2 = prev1;
            prev1 = cur;
        }
        System.out.println(prev1);
    }
}
#include <bits/stdc++.h>
using namespace std;

int main() {
 int n; cin >> n;
 int prev2 = 0, prev1 = 0;
 for (int i = 0; i < n; i++) {
 int x; cin >> x;
 int cur = max(prev1, prev2 + x);
 prev2 = prev1;
 prev1 = cur;
 }
 cout << prev1;
}

Find the element which is largest in its row and smallest in its column in a matrix. If no such element exists, print -1.

Input: N M then N rows of M non-negative integers. Constraints

1 ≤ N, M ≤ 1000.

2 2
1 2
3 4
→ 2

解法

预处理 rowMax[i](第 i 行最大值所在列)和 colMin[j](第 j 列最小值所在行)。(i, j) 是鞍点当且仅当 j == rowMax[i]i == colMin[j]。复杂度 O(N · M)

def saddle_point(a: list[list[int]]) -> int:
    n, m = len(a), len(a[0])
    row_max_col = [max(range(m), key=lambda j: a[i][j]) for i in range(n)]
    col_min_row = [min(range(n), key=lambda i: a[i][j]) for j in range(m)]
    for i in range(n):
        j = row_max_col[i]
        if col_min_row[j] == i:
            return a[i][j]
    return -1
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(), m = sc.nextInt();
        int[][] a = new int[n][m];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++) a[i][j] = sc.nextInt();
        int[] rowMaxCol = new int[n], colMinRow = new int[m];
        for (int i = 0; i < n; i++) {
            int idx = 0;
            for (int j = 1; j < m; j++) if (a[i][j] > a[i][idx]) idx = j;
            rowMaxCol[i] = idx;
        }
        for (int j = 0; j < m; j++) {
            int idx = 0;
            for (int i = 1; i < n; i++) if (a[i][j] < a[idx][j]) idx = i;
            colMinRow[j] = idx;
        }
        for (int i = 0; i < n; i++) {
            int j = rowMaxCol[i];
            if (colMinRow[j] == i) { System.out.println(a[i][j]); return; }
        }
        System.out.println(-1);
    }
}
#include <bits/stdc++.h>
using namespace std;

int main() {
 int n, m; cin >> n >> m;
 vector<vector<int>> a(n, vector<int>(m));
 for (int i = 0; i < n; i++)
 for (int j = 0; j < m; j++) cin >> a[i][j];
 vector<int> rowMaxCol(n), colMinRow(m);
 for (int i = 0; i < n; i++) {
 int idx = 0;
 for (int j = 1; j < m; j++) if (a[i][j] > a[i][idx]) idx = j;
 rowMaxCol[i] = idx;
 }
 for (int j = 0; j < m; j++) {
 int idx = 0;
 for (int i = 1; i < n; i++) if (a[i][j] < a[idx][j]) idx = i;
 colMinRow[j] = idx;
 }
 for (int i = 0; i < n; i++) {
 int j = rowMaxCol[i];
 if (colMinRow[j] == i) { cout << a[i][j]; return 0; }
 }
 cout << -1;
}

A binary number is represented as a series of 0s and 1s in the form of a single-linked list. Given a reference of the head, convert the binary number to a decimal number (head = MSB).

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

A company's IT department is faced with a dilemma that users keep using simple passwords such as "password", "abc123" etc. Write an algorithm to identify the total minimum number of changes (insertions and deletions) of characters to convert these simple passwords to their more difficult versions.

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

In a hostel, there are birthday celebrations every month. Find the number of days where there are an odd number of birthday celebrations.

Input: N then N date numbers. Output: number of dates that appear an odd number of times.

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

Given a list of integers, find out if the elements are prime or composite. Print Prime or Composite, one per line.

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

Write an algorithm to add the numbers and print them as a list. Input The first line of input consists of an integer- list1_size, representing the size of the first list (N). The second line consists of N space-separated integers representing the elements in the first list. The third line of input consists of an integer- list2_size, representing the size of the second list (M). The last line consists of M space-separated integers representing the elements in the second list. Output Print K space-separated integers representing the digits in reverse order which are the sum of both the numbers.

Example 1

Input:

list1 = [2, 4, 6]
list2 = [8, 0, 9]

Output:

[0, 5, 5, 1]

Explanation: The given lists are [2,4,6], [8,0,9], so the two numbers are '642' and '908'. The sum of both the numbers is 642+908=1550. So the output is [0, 5, 5, 1].

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

Given an integer array inputNums, return [mean, mode] where mean is the integer floor of the average and mode is the most frequently occurring value (if multiple values tie, return the smallest one).

Constraints

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

Example 1

Input:

inputNums = [1, 2, 7, 3, 2]

Output:

[3, 2]

Explanation: The mean for the given set of numbers is 3 (1+2+7+3+2 = 15, 15/2=3). The mode is the most frequently occurring number which is 2. So, the output is 3, 2.

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

Given a string inputString, find the first index i (1-indexed in the original wording but use 0-based zero-indexing here) at which the string breaks lowercase alphabetical (non-decreasing) order — that is, the first i ≥ 1 with inputString[i] < inputString[i-1]. If the entire string is already in non-decreasing order, return 0.

Constraints

  • 1 ≤ len(inputString) ≤ 10⁵
  • inputString consists of lowercase English letters.

Example 1

Input:

inputString = "abc"

Output:

0

Explanation: The given string "abc" is in alphabetical order, so the output is '0'.

Example 2

Input:

inputString = "asd"

Output:

2

Explanation: The given string "asd" is not in alphabetical order, and the character at index '2' is where it is out of order.

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

A player has to collect coins from various locations. The city is represented as a tree with n vertices labelled from 0 to n-1. There is an array called coins of size n where coins[i] is either 0 or 1, 1 means coin present and vice versa. The player must travel along the tree to collect all the coins. The distance between two vertices is the edge connecting the points and if the player is at x then he can only collect coins that are located within distance of 2 edges of that vertex x. The player can choose any vertex to start but then must end at that starting vertex only. All edges are bidirectional. We need to return the number of edges in the shortest path such that all coins are collected. Function Description Complete the function collectCoins in the editor. collectCoins has the following parameters:

    1. int treeNodes: the number of vertices in the tree
    1. vector &coins: an array where each element is either 0 or 1
    1. vector &tree_from: an array representing one endpoint of an edge
    1. vector &tree_to: an array representing the other endpoint of an edge Returns int: the number of edges in the shortest path to collect all coins
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given a sorted list of integers with no duplicates, write an algorithm to compact the list based on a continuous range of numbers. If there are no such ranges available, print the list of strings where each element is a string notation of the number. Input The first line of input consists of an integer inputListSize, representing the number of elements in the list (N). The next line consists of N space-separated integers representing the elements of the list. Output Print a line-separated list of strings which represents the compacted form of the given list based on a continuous range of numbers. Note List is sorted in ascending order.

Constraints

  • 1 ≤ N ≤ 10⁵
  • Elements are distinct integers in [-10⁹, 10⁹].

Example 1

Input:

inputListSize = 8
inputList = [1, 2, 3, 6, 7, 8, 10, 15]

Output:

["1 to 3", "6 to 8", "10", "15"]

Explanation: In the given list 1,2,3 form a continuous range and hence are compacted to "1 to 3" and the same for 6,7,8 which are compacted to "6 to 8". But 10 and 15 cannot be compacted so are printed as they are.

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

A company's IT department is faced with a dilemma that users keep using simple passwords such as "password", "abc123" etc. You are tasked with a challenge to write an algorithm to identify the total minimum number of changes (insertions and deletions) of characters to convert these simple passwords to their more difficult versions. Input The first line of input consists of a string-currPassword, representing the current password. The second line consists of a string-newPassword, representing the new password. Output Print an integer representing the minimum number of updates required (character insertions and deletions) to convert the current password into the new password.

Constraints

  • 1 ≤ len(currPassword), len(newPassword) ≤ 1000

Example 1

Input:

currPassword = "password"
newPassword = "pss$w#rd"

Output:

4

Explanation: The current password is "password" and the new password is "pss$w#rd"; we need to delete 'a' and 'o' (2 operations) and insert '$' and '#' (2 operations) to convert the current password into the new password. So, the output is 4.

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

Given an integer X, write an algorithm to find the number of integers which are less than or equal to X and whose digits add up to Y. Description Input The first line of input consists of an integer - inputNum1, representing the given number X. The next line consists of an integer - inputNum2, representing the given number Y. Output Print the count of numbers whose digits add up to Y for the given number X. Note If no numbers are found whose digits add up to Y for the given number X, then print -1.

Constraints

  • 1 ≤ X ≤ 10⁶
  • 1 ≤ Y ≤ 54 (digit sum of a 6-digit number is at most 9 × 6 = 54)

Example 1

Input:

inputNum1 = 20
inputNum2 = 5

Output:

2

Explanation: X is 20 and Y is 5. There are only 2 integers ≤ 20, i.e., 5 and 14 whose digits add up to 5.

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

Given a string s mixing letters and single digits, build an output string by scanning s left to right:

  • Letters accumulate into a buffer buf.
  • A digit d flushes the buffer: append buf to the output d times (so d == 1 keeps it once; d == 0 discards it).
  • Whatever letters remain in buf at the end are appended as-is.

Return the resulting string.

Constraints

  • 1 ≤ len(s) ≤ 10⁴
  • s contains lowercase letters and digits 0-9.

Example 1

Input:

s = "cisco"

Output:

"cisco"

Explanation: The given string is "cisco" and contains all letters so add it to the output string (using rule number 1). So, the output will be "cisco".

Example 2

Input:

s = "cisco2india"

Output:

"ciscociscoindia"

Explanation: The given string is "cisco2india" which contains one digit '2' after "cisco" so by using rule number 2, we get "ciscocisco" and the remaining substring "india" it is added to the output string using rule number 1. So, the output is "ciscociscoindia".

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

Write an algorithm to expand the given string by using the given rules. Input The input consists of a string - inputStr, representing the substring(s) grouped by using parenthesis (S). Output Print the string by expanding it in such a way that P will be concatenated with itself N_n times to expand.

Example 1

Input:

inputStr = "(ab)(3)"

Output:

"ababab"

Explanation: In the given string S = "(ab)(3)", P_1=ab, N_1=3. So, to expand string S, pattern P_1 will be concatenated N_1 times as "ab" + "ab" + "ab" to give the final output. So, the output is "ababab".

Example 2

Input:

inputStr = "(ab)(3)(cd)(2)"

Output:

"abababcdcd"

Explanation: In the given string S = "(ab)(3)(cd)(2)", P_1=ab, N_1=3 and P_2=cd, N_2=2.

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

A system contains pods numbered from 1 to n, distributed across multiple geographical regions. These pods are interconnected by n links, represented by the array connections, such that if two pods are connected directly or indirectly, they belong to the same region. Each pod has a database connection to which it writes the critical data received. If a pod loses its database connection for some reason, it forwards the data to an active pod in the same region with the lowest ID, and that pod writes the data to the region's database. If there are no active pods left in the region, the data is not written, and an error is recorded in the logs. Process q queries of two types: a data-sending query of the form "1 pod_id," or a database-connection-failure query of the form "2 pod_id." For each data-sending query, the program should output the ID of the pod that writes the data to the database. Specifically, when a data-sending query is made to pod sender_pod_id, the program should find the active pod in the same region with the lowest ID and return its ID as the output. If there are no active pods in the region, the program should output -1.

Constraints

  • 1 ≤ n, q ≤ 10⁵
  • 1 ≤ connections[i][0], connections[i][1] ≤ pods
  • Each query is either [1, pod_id] or [2, pod_id].

Example 1

Input:

pods = 3
n = 2
connections = [[1, 2], [2, 3]]
q = 5
queries = [[2, 2], [1, 2], [2, 1], [2, 3], [1, 1]]

Output:

[1, -1]

Explanation:

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

Write an algorithm which finds out the elements which are largest in a row and smallest in a column in a matrix. Input The first line of input consists of two space-separated integers- matrix_row and matrix_col, representing the number of rows in the matrix (N) and the number of columns in the matrix (M), respectively. The next M lines consist of N space-separated integers representing the elements of the matrix. Output Print a number which is largest in a row and smallest in a column in the given matrix. If no element is found print '-1'. Note Each number in the matrix is a non-negative integer.

Constraints

1 ≤ N, M ≤ 1000

Example 1

Input:

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

Output:

2

Explanation: The number 2 at index (0,1) is the largest in its row and smallest in its column. So, the output is 2.

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

You are given a list of integers (both positive and negative). Find the continuous sequence of integers with the largest sum. Write an algorithm to find the largest sum of the continuous sequence from the given list. Input The first line of input consists of an integer - inputArr_size, representing the size of the list (N). The next line consists of N space-separated integers representing the elements of the list. Output Print an integer representing the largest sum of the continuous sequence from the given list.

Example 1

Input:

inputArr = [2, -8, 3, -2, 4, -10]

Output:

5

Explanation: The given list is (2, -8, 3, -2, 4, -10), and we take (3, -2, 4) as the continuous sequence for getting the largest sum. The sum is 3+ (-2) +4, which is 5.

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

Lucy loves to play the Hop, Skip and Jump game. Given an N*M matrix and starting from cell (1,1), her challenge is to hop in an anti-clockwise direction and skip alternate cells. The goal is to find out the last cell she would hop onto. Write an algorithm to find the last cell Lucy would hop onto after moving anti-clockwise and skipping alternate cells. Input The first line of input consists of two integers- matrix_row and matrix_col, representing the number of rows (N) and the number of columns (M) in the matrix, respectively. The next M lines consist of N space-separated integers representing the elements in each cell of the matrix. Output Print an integer representing the last cell Lucy would hop onto after following the given instructions.

Example 1

Input:

matrix = [[29, 8, 37], [15, 41, 3], [1, 10, 14]]

Output:

41

Explanation: Lucy starts with 29, skips 15, hops onto 1, skip 10, hops onto 14, skips 3, hops onto 37, skips 8 and finally hops onto 41. So, the output is 41.

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

The input consists of a string inputStr, representing the given string for the puzzle. From the given string, print a substring which is the same when read forwards and backwards. Note

  • If there are multiple sub-strings of equal length, choose the lexicographically smallest one.
  • If there are multiple sub-strings of different length, choose the one with maximum length.
  • If there is no sub-string that is the same when read forwards and backwards print "None".
  • Sub-string is only valid if its length is more than 1.
  • Strings only contain uppercase characters (A-Z).

Constraints

  • 1 ≤ len(inputStr) ≤ 1000

Example 1

Input:

inputStr = "YABCCBAZ"

Output:

"ABCCBA"

Explanation: Given string is "YABCCBAZ", in this only sub-string which is same when read forward and backward is "ABCCBA".

Example 2

Input:

inputStr = "ABC"

Output:

"None"

Explanation: Given string is "ABC", and no sub-string is present which is same when read forward and backward. So, the output is "None".

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

Given a list of integers, find the maximum difference of two elements where the larger number appears after the smaller number. Write an algorithm to find the maximum difference of two elements where the larger number appears after the smaller number. Input The first line of input consists of an integer - inputArray_size, representing the size of the list (N). The next line consists of N space-separated integers representing the elements of the list. Output Print an integer representing the maximum difference of the two elements where the larger number appears after the smaller number. If no such elements are found, print 0.

Example 1

Input:

n = 7
inputArray = [2, 3, 10, 6, 4, 8, 1]

Output:

8

Explanation: From the given list, the maximum difference will be 8 (difference between 2 and 10 :), we won't consider (10 and 1), as the larger number should appear after the smaller one. So, the output is 8

Example 2

Input:

n = 3
inputArray = [4, 3, 1]

Output:

0

Explanation: Will add once find reliable source :) Just like what we did for the example 1 above See yall next time!

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

Given parallel arrays x and y representing 2D points (x[i], y[i]), a pilot flies a single straight line that is either fully horizontal or fully vertical. Return the maximum number of points that lie on any single horizontal line (y = c) or vertical line (x = c). A "valid path" must contain at least two points; if every line covers at most one point, return 0.

Constraints

  • 1 ≤ len(x) == len(y) ≤ 700

Example 1

Input:

x = [2, 3, 2, 4, 2]
y = [2, 2, 6, 5, 8]

Output:

3

Explanation: There are 5 coordinates- (2,2), (3,2), (2,6), (4,5) and (2,8). The best path is the horizontal one covering (2,2), (2,6) and (2,8). So, the output is 3 :)

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

There are n regions hosting servers. Region i has machineCount[i] machines. Two operations are allowed:

  • Adjust: add or remove a single machine in some existing region. The region's count must stay positive both before and after. Cost: 1 unit per machine added or removed.
  • Move: transfer every machine from one region into another existing region. The source region becomes empty and is destroyed. Cost: shiftingCost units.

Find the minimum total cost so that some 3 regions end up with the multiset of counts in finalMachineCount. Extra machines / extra regions outside those 3 are allowed.

Constraints

  • 3 ≤ n ≤ 10
  • 1 ≤ machineCount[i], finalMachineCount[i] ≤ 10⁶
  • len(finalMachineCount) == 3

Example 1

Input:

machineCount = [2, 4, 5, 3]
finalMachineCount = [4, 4, 4]
shiftingCost = 5

Output:

2

Explanation: On increasing the number of machines of the 4^th region by 1 and decreasing the number of machines of the 3^rd region by 1, the new machineCount = [2, 4, 4, 4]. Total cost for these operations = 1+1=2. Use the 2^nd, 3^rd, and 4^th regions as the required servers, leaving behind the 1^st region.

Example 2

Input:

machineCount = [2, 3, 5, 7]
finalMachineCount = [5, 10, 5]
shiftingCost = 2

Output:

2

Explanation: On increasing the number of machine in the 1st and 2nd regions by 1 and 2 machines respectively, the new machineCost = [2, 3, 5, 7]. Total cost for these operations = 1 + 2 = 3. Now, moving all the machines form th 4th region to 1st, which takes shiftingCost = 2, the new machineCost = [10, 5, 5]. The cost of this operation is 2. Therefore, the total cost = 3 +2 = 5 :) (Can confirm that the second example & explanation & constraints are accurate and original. I'm just being a bit lazy about uploading another source image atm :)

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

Input The first line of input consists of two space-separated integers- matrix_row and matrix_col, representing the number of rows in the matrix (N) and the number of columns in the matrix (M), respectively. The next M lines consist of N space-separated integers representing the elements of the matrix. Output Print a number which is largest in a row and smallest in a column in the given matrix. If no element is found print "-1".

Constraints

  • 1 ≤ N, M ≤ 1000
  • Each matrix entry is a non-negative integer.

Example 1

Input:

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

Output:

2

Explanation: The number 2 at index (0,1) is the largest in its row and smallest in its column. So, the output is 2.

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

You are given a grid of letters, followed by some words. The words can occur anywhere in the grid on a row or a column, forward or backwards. However, there are no diagonal words. Write an algorithm to find if the given word occurs in the grid on a row or a column, forward or backwards. Input The first line of input consists of two integers- grid_row and grid_col, representing the number of rows (N) and the number of columns (M) of the letter grid, respectively. The next M lines consist of N space-separated characters representing the letters of the grid The next line consists of an integer- word_size, representing the number of words to be searched from the given grid (K) The last line consists of K space-separated strings representing the words to search for in the grid. Output Print K space-separated strings consisting of "Yes" if the word is present in the grid or "No" if the word is not present in the grid. Note All the inputs are case-sensitive, meaning "a" and "A" are considered as two different characters.

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

In a neural network, there are nodes representing servers capturing neural signals in a cutting-edge machine learning application. Akin to the architecture of a neural network, there are server_nodes servers, where the ith server captures the signal of minimum neural activity represented by minActivity[i]. The servers are connected in a tree structure with server_nodes - 1 connections, where the ith connection connects the servers server_from[i] and server_to[i] and the change in neural activity of the signal traveling the ith connection is represented by server_weight[i]. The neural activity of a signal transmitted from server x and reaching server y is the sum of the neural activity change by traveling across the path from x to y. Note: All the servers transmit the signals of activity 0. The tree is rooted at server 1. It is possible for a signal to have negative neural activity as well. The neural activity of a signal after passing through a connection improves or deteriorates, depending on whether the server_weight[i] is positive or negative respectively. A server u is said to be vulnerable if there exists a server v (≠ u) in the subtree of u such that: The neural activity of the signal reaching server v from server u is greater than minActivity[v]. Note: A subtree of a node x is a tree containing all the children of x and having x as the root. The server can be disconnected in the following way: Choose a leaf node from the remaining tree and remove that server. The task is to determine the minimum number of servers that need to be disconnected such that no server remains vulnerable. Function Description Complete the function getMinServers in the editor. getMinServers has the following parameters:

  • int server_nodes: the number of servers
  • vector server_from: the server from which the signal is sent
  • vector server_to: the server to which the signal is sent
  • vector server_weight: the change in neural activity due to the signal passing through the server
  • vector minActivity: the minimum neural activity that a server can handle without being vulnerable Returns int: the minimum number of servers that need to be disconnected

Constraints

3 ≤ server_nodes ≤ 2 * 10⁵ 1 ≤ server_from[i], server_to[i] ≤ server_nodes -10⁹ ≤ server_weight[i] ≤ 10⁹ -10⁹ ≤ minActivity[i] ≤ 10⁹

Example 1

Input:

server_nodes = 5
server_from = [1, 1, 3, 3]
server_to = [2, 3, 4, 5]
server_weight = [-2, 5, -5, -3]
minActivity = [0, -10, 5, -5, 5]

Output:

2

Explanation: Server 1 is vulnerable because the signal reaching server 4 from 1 has activity 0 (which is > -5), so server 4 is removed. Server 1 is still vulnerable because the signal reaching server 2 from 1 has activity -2 (which is > -10), so server 2 is removed. Hence, the answer is 2.

Example 2

Input:

server_nodes = 4
server_from = [1, 1, 2]
server_to = [2, 3, 3]
server_weight = [3, 4]
minActivity = [1, 2, 3, 4]

Output:

1

Explanation: In this case, you need to disconnect at least one server to ensure no server is vulunerable.

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

Ray, Shiv and Ansh are conducting a survey for a group of people. The survey is only meant for twins but there are certain people who are not twins and wanting to take part in the survey. Write an algorithm to help them identify the person from the given input who is not a twin. Input The first line of input consists of an integer- inputArr_size, representing the number of entries in the array (N). The next line consists of N space-separated integer elements in the array. Output Print the smallest value of the person who is not a twin from the given array of elements. Note: If everyone present is a twin, then return -1.

Example 1

Input:

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

Output:

2

Explanation: In the given array of element, only non-twin element is '2'. So, the output is 2.

Example 2

Input:

inputArr = [1, 1, 2, 2]

Output:

-1

Explanation: Given array of element contain all the twin elements. So, the output is -1.

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

Given a string s, return the longest palindromic substring of s. If multiple substrings of the same maximum length exist, any one of them is acceptable. (LeetCode 5.)

Constraints

  • 1 ≤ len(s) ≤ 1000
  • s consists of digits and English letters.

Example 1

Input:

s = "babad"

Output:

"bab"

Explanation: "aba" is also a valid answer.

Example 2

Input:

s = "cbbd"

Output:

"bb"

Explanation:

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

There are N jars in a line, each holding some chocolates (possibly zero). Pick chocolates from a subset of jars such that no two chosen jars are adjacent. Return the maximum total chocolates picked.

Constraints

  • 1 ≤ N ≤ 1000
  • 0 ≤ jars[i] ≤ 10⁴

Example 1

Input:

jars = [5, 30, 99, 60, 5, 10]

Output:

114

Explanation: Andrew picks from the 1st (5), 3rd (99) and 6th (10) jars. So, the output is 114. Explanation added on 03-13-2025 :)

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

Given a singly linked list and an integer, x, remove nodes greater than x. Example: List = 100 → 105 → 50 x = 100 List becomes 100 → 50 Return a reference to the root node of the list after removing 105. Function Description Complete the function removeNodes in the editor with the following parameter(s):

  • node listHead: a reference to the root node of the singly-linked list
  • int x: the maximum value to be included in the returned singly-linked list Returns: node: a reference to the root node of the final list

Constraints

  • 1 ≤ n, x ≤ 10⁵
  • 1 ≤ node.val ≤ 10⁵
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given a matrix of N*M size. Write an algorithm to rotate the matrix by 90 degrees. Input The first line of input consists of two integer- inputMat_row and inputMat_col, representing the number of row (N) and column (M) of the matrix. The next M lines consist of N space-separated integers representing the elements of the matrix. Output Print the matrix after rotating it by 90 degrees. Note Number of rows (N) and number of columns (M) will always be same.

Example 1

Input:

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

Output:

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

Explanation: We have to rotate the given matrix by 90 degrees, so we will rotate each and every element of the matrix in clockwise direction, and we get "7 4 1", "8 5 2", "9 6 3" in each row.

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

Given 4 Jugs namely [J1, J2, J3, J4] with capacities [C1, C2, C3, C4] and initial water content as [S1, S2, S3, S4]. Determine how many steps are needed to achieve the final state of [F1, F2, F3, F4] by transferring water from one jug to another without losing any water. Input: Total number of entries = 13 First line specifies the number of entries in the array, which is 12 in our case Next 4 lines contain the capacities of the 4 jugs Next 4 lines contain the initial content of the 4 jugs Next 4 lines contain the final content of the 4 jugs Output: The minimum number of steps required to reach Final State (F) from Initial State (S). Return -1 if not possible.

Constraints

  • 0 < Cᵢ ≤ 100
  • 0 ≤ Sᵢ ≤ Cᵢ, 0 ≤ Fᵢ ≤ Cᵢ
  • Sum(Sᵢ) == Sum(Fᵢ) (no water is lost)

Example 1

Input:

capacities = [12, 13, 12, 10]
initial = [6, 6, 0, 0]
target = [12, 0, 0, 0]

Output:

1

Explanation: In one step, we can transfer 6 units of water from J1 and J2 to J3, achieving the final state of [12, 0, 0, 0].

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

解锁全部 30 道题的解法

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

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

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