OAmaster
— / 391已做

An application at Amazon is deployed on n servers connected linearly. The vulnerability of the i-th server is given by vulnerability[i]. The system vulnerability of a contiguous segment of servers is defined as the number of servers in the segment × the maximum vulnerability of the segment. Given the vulnerability array, find the sum of system vulnerabilities of all the segments (subsegments) of the servers. Since the answer can be very large, report it modulo 10⁹ + 7.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ vulnerability[i] ≤ 10⁹

Example

vulnerability = [3, 1, 4]
answer = 34
Subsegmentserversmaxsystem vuln
[3]133
[3,1]236
[3,1,4]3412
[1]111
[1,4]248
[4]144

解法

单调栈。对每个 i 找左侧严格更大、右侧 ≥ 的最近下标,设 l = i - left[i]r = right[i] - iv[i] 作为最大值时对所有子段的贡献为 v[i] · l · r · (l + r) / 2。复杂度 O(n)

def getSystemVulnerability(vulnerability):
    MOD = 10**9 + 7
    INV2 = pow(2, MOD - 2, MOD)
    n = len(vulnerability)

    left = [-1] * n
    stack = []
    for i in range(n):
        while stack and vulnerability[stack[-1]] <= vulnerability[i]:
            stack.pop()
        left[i] = stack[-1] if stack else -1
        stack.append(i)

    right = [n] * n
    stack = []
    for i in range(n - 1, -1, -1):
        while stack and vulnerability[stack[-1]] < vulnerability[i]:
            stack.pop()
        right[i] = stack[-1] if stack else n
        stack.append(i)

    ans = 0
    for i in range(n):
        l = i - left[i]
        r = right[i] - i
        contrib = vulnerability[i] * l % MOD * r % MOD * (l + r) % MOD * INV2 % MOD
        ans = (ans + contrib) % MOD
    return ans
import java.util.*;

class Solution {
    public int getSystemVulnerability(List<Integer> vulnerability) {
        final long MOD = 1_000_000_007L;
        final long INV2 = (MOD + 1) / 2;
        int n = vulnerability.size();
        int[] v = new int[n];
        for (int i = 0; i < n; i++) v[i] = vulnerability.get(i);

        int[] left = new int[n];
        Deque<Integer> stack = new ArrayDeque<>();
        for (int i = 0; i < n; i++) {
            while (!stack.isEmpty() && v[stack.peek()] <= v[i]) stack.pop();
            left[i] = stack.isEmpty() ? -1 : stack.peek();
            stack.push(i);
        }

        int[] right = new int[n];
        stack.clear();
        for (int i = n - 1; i >= 0; i--) {
            while (!stack.isEmpty() && v[stack.peek()] < v[i]) stack.pop();
            right[i] = stack.isEmpty() ? n : stack.peek();
            stack.push(i);
        }

        long ans = 0;
        for (int i = 0; i < n; i++) {
            long l = i - left[i];
            long r = right[i] - i;
            long contrib = v[i] % MOD * l % MOD * r % MOD * ((l + r) % MOD) % MOD * INV2 % MOD;
            ans = (ans + contrib) % MOD;
        }
        return (int) ans;
    }
}
#include <vector>
#include <stack>
using namespace std;

class Solution {
public:
    int getSystemVulnerability(vector<int>& vulnerability) {
        const long long MOD = 1'000'000'007LL;
        const long long INV2 = (MOD + 1) / 2;
        int n = vulnerability.size();
        vector<int> left(n), right(n);
        stack<int> st;

        for (int i = 0; i < n; i++) {
            while (!st.empty() && vulnerability[st.top()] <= vulnerability[i]) st.pop();
            left[i] = st.empty() ? -1 : st.top();
            st.push(i);
        }
        while (!st.empty()) st.pop();

        for (int i = n - 1; i >= 0; i--) {
            while (!st.empty() && vulnerability[st.top()] < vulnerability[i]) st.pop();
            right[i] = st.empty() ? n : st.top();
            st.push(i);
        }

        long long ans = 0;
        for (int i = 0; i < n; i++) {
            long long l = i - left[i];
            long long r = right[i] - i;
            long long contrib = (long long)vulnerability[i] % MOD * l % MOD * r % MOD * ((l + r) % MOD) % MOD * INV2 % MOD;
            ans = (ans + contrib) % MOD;
        }
        return (int) ans;
    }
};

Amazon Technical Academy (ATA) provides on-demand technical training to current Amazon employees looking to broaden their skill sets. ATA has admitted a group of n prospective trainees with varying skill levels. To better accommodate the trainees, ATA has decided to create classes tailored to the skill levels. A placement examination will return a skill level that will be used to group the trainees into classes, where levels[i] represents the skill level of trainee i. All trainees within a class must have a skill level within maxSpread of one another. Determine the minimum number of classes that must be formed.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ levels[i] ≤ 10⁹ for every i (where 0 ≤ i ≤ n-1)
  • 0 ≤ maxSpread ≤ 10⁹

Example

n = 4
levels = [4, 8, 1, 7]
maxSpread = 3
answer = 2

解法

排序后贪心:当前元素超过 start + maxSpread 时开一组新班。复杂度 O(n log n)

def groupStudents(levels, maxSpread):
    levels.sort()
    classes = 1
    start = levels[0]
    for x in levels:
        if x - start > maxSpread:
            classes += 1
            start = x
    return classes
import java.util.*;

class Solution {
    public int groupStudents(int[] levels, int maxSpread) {
        Arrays.sort(levels);
        int classes = 1;
        int start = levels[0];
        for (int x : levels) {
            if (x - start > maxSpread) {
                classes++;
                start = x;
            }
        }
        return classes;
    }
}
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    int groupStudents(vector<int>& levels, int maxSpread) {
        sort(levels.begin(), levels.end());
        int classes = 1;
        int start = levels[0];
        for (int x : levels) {
            if (x - start > maxSpread) {
                classes++;
                start = x;
            }
        }
        return classes;
    }
};

Software developers at Amazon are developing a new library for natural language processing. In one of its modules, every string needs to be preprocessed in a particular manner to find the length of its longest self-sufficient proper substring. A substring is self-sufficient if every character appearing in it appears the same total number of times in the original string. A proper substring is a substring that is not equal to the whole string. Find the length of the longest self-sufficient proper substring of fullString. If no such substring exists, return 0.

Constraints

  • 1 ≤ |fullString| ≤ 10⁵
  • fullString consists of lowercase English letters

Example

fullString = "abadgdg"
answer = 4
fullString = "aaaaaaa"
answer = 0

解法

贪心划分:自足块是包含其内每个字符所有出现的最小连续区间。求出所有此类块;若 ≥ 2 个,答案为 max(最大块, 总长 - 最小块)。复杂度 O(n)

def findLongestLength(fullString):
    n = len(fullString)
    last = {c: i for i, c in enumerate(fullString)}

    blocks = []
    l = 0
    r = last[fullString[0]]
    for i in range(n):
        r = max(r, last[fullString[i]])
        if i == r:
            blocks.append(r - l + 1)
            l = r + 1
            if l < n:
                r = last[fullString[l]]

    if len(blocks) < 2:
        return 0
    total = sum(blocks)
    return max(max(blocks), total - min(blocks))
import java.util.*;

class Solution {
    public int findLongestLength(String fullString) {
        int n = fullString.length();
        int[] last = new int[26];
        for (int i = 0; i < n; i++) last[fullString.charAt(i) - 'a'] = i;

        List<Integer> blocks = new ArrayList<>();
        int l = 0, r = last[fullString.charAt(0) - 'a'];
        for (int i = 0; i < n; i++) {
            r = Math.max(r, last[fullString.charAt(i) - 'a']);
            if (i == r) {
                blocks.add(r - l + 1);
                l = r + 1;
                if (l < n) r = last[fullString.charAt(l) - 'a'];
            }
        }

        if (blocks.size() < 2) return 0;
        int total = 0, maxLen = 0, minLen = Integer.MAX_VALUE;
        for (int b : blocks) {
            total += b;
            maxLen = Math.max(maxLen, b);
            minLen = Math.min(minLen, b);
        }
        return Math.max(maxLen, total - minLen);
    }
}
#include <string>
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;

class Solution {
public:
    int findLongestLength(string fullString) {
        int n = fullString.size();
        int last[26] = {0};
        for (int i = 0; i < n; i++) last[fullString[i] - 'a'] = i;

        vector<int> blocks;
        int l = 0, r = last[fullString[0] - 'a'];
        for (int i = 0; i < n; i++) {
            r = max(r, last[fullString[i] - 'a']);
            if (i == r) {
                blocks.push_back(r - l + 1);
                l = r + 1;
                if (l < n) r = last[fullString[l] - 'a'];
            }
        }

        if ((int) blocks.size() < 2) return 0;
        int total = 0, maxLen = 0, minLen = INT_MAX;
        for (int b : blocks) {
            total += b;
            maxLen = max(maxLen, b);
            minLen = min(minLen, b);
        }
        return max(maxLen, total - minLen);
    }
};

In this problem, you are given an integer array arr and you need to perform some operations on the array to make all its elements equal to 0. In one operation, you can select a prefix of the array and either increment all the elements of the prefix by 1 or decrement all the elements of the prefix by 1. Find the minimum number of operations to convert every element of arr to 0.

Constraints

  • 1 ≤ n ≤ 10⁵
  • −10⁹ ≤ arr[i] ≤ 10⁹

Example

arr = [3, 2, 0, 0, -1]
answer = 5
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

A team of financial analysts at Amazon has designed a stock indicator to determine the consistency of Amazon's stock in delivering returns daily. The percentage return delivered by the stock each day over the last n days is given as stockPrices (values may be negative). The consistency score is the maximum length of any contiguous subarray stockPrices[l..r] such that every prefix sum within the subarray (i.e. stockPrices[l] + stockPrices[l+1] + … + stockPrices[m] for every l ≤ m ≤ r) is non-negative. Return that maximum length.

Constraints

  • 1 ≤ n ≤ 10⁵
  • −10⁹ ≤ stockPrices[i] ≤ 10⁹

Example

stockPrices = [1, 1, 2, 3, 1]
k = 0
answer = 5
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Amazon Games has launched a two-player game with an array of positive integer points. Each turn, a player picks any integer, adds it to their score, and removes it. Players 1 and 2 alternate with player 1 first. The game ends when the array is empty. Both want to maximize their own score. Find the absolute difference of the two players' scores when both play optimally.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ points[i] ≤ 10⁹

Example

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

Amazon Games launched a 3-round tournament. Each player has exactly three power boosters. In each round a player picks one booster; higher booster wins the round. Player X "defeats" player Y if some rearrangement of X's three boosters beats Y in at least 2 rounds (against any rearrangement of Y). Count players who can defeat every other player.

Constraints

  • 2 ≤ n ≤ 10⁵
  • 1 ≤ booster_a[i], booster_b[i], booster_c[i] ≤ 10⁹

Example

n = 4
booster_a = [3, 4, 1, 16]
booster_b = [2, 11, 5, 6]
booster_c = [8, 7, 9, 10]
answer = 2
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Amazon's analytics team tracks how data on the n-th item depends on other days. The data on item n is said to depend on day x if there exists some positive integer k such that floor(n / k) = x (where 0 ≤ x ≤ n). Given n, find the sum of all distinct values of x for which such a k exists.

Constraints

  • 1 ≤ n ≤ 10¹⁰

Example

n = 5
answer = 8
xkfloor(n / k)
06floor(5/6) = 0
15floor(5/5) = 1
22floor(5/2) = 2
51floor(5/1) = 5
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given an integer array arr of size n. Exactly n − 2 of the elements are "normal" numbers. One of the remaining two elements equals the sum of those n − 2 normal numbers, and the other element is the outlier. (The sum element and the outlier element have distinct indices in arr, but may share the same numeric value.) Return the largest possible outlier value across all valid choices of which n − 2 elements are the normal ones.

Constraints

  • 3 ≤ n ≤ 10⁵
  • 1 ≤ arr[i] ≤ 10⁹

Example

n = 4
arr = [4, 1, 2, 10]
answer = 4
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Amazon uses a Pascal-triangle style encryption on numeric tokens. Given an array numbers of single digits (each in 0..9), repeatedly replace the array with a new array of length len(arr) − 1 in which the i-th entry equals (arr[i] + arr[i+1]) mod 10. Continue until exactly 2 digits remain. Return the final encrypted value as a 2-character string (left-padded so the output always has length 2).

Constraints

  • 2 ≤ n ≤ 10⁵
  • 0 ≤ numbers[i] ≤ 9

Example

numbers = [4, 5, 6, 7]
answer = "04"
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Amazon developers are building a regex generator. The regex consists of uppercase English letters, [, and ]. A bracketed group contains distinct uppercase letters and matches any single character in the group. Given strings x, y, z of length n, find the longest lexicographically smallest regex that matches both x and y but does not match z. Return -1 if impossible.

Constraints

  • 1 ≤ n ≤ 10⁶
  • x, y, z consist of uppercase English letters only.

Example

x = "AB", y = "BD", z = "CD"
answer = "[ABDEFGHIJKLMNOPQRSTUVWXYZ][ABCDEFGHIJKLMNOPQRSTUVWXYZ]"
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

There are n points; the i-th has weight weight[i] and starts at position i on the x-axis. In one operation, the i-th point moves right by dist[i]. Find the minimum total number of operations to sort the points by weight.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ weight[i], dist[i] ≤ 10⁹

Example

n = 4
weight = [3, 6, 5, 1]
dist = [4, 3, 2, 1]
answer = 5
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Amazon Web Services has n servers with capacities. A contiguous segment [l, r] (with r - l + 1 >= 3) is balanced iff capacity[l] == capacity[r] == sum(capacity[l+1..r-1]). Count balanced subsegments.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ capacity[i] ≤ 10⁹

Example

capacity = [9, 3, 3, 3, 9]
answer = 2
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

For each pair (newPasswords[i], oldPasswords[i]), return "YES" if there is a way to "cycle-shift" some characters of newPasswords[i] (each chosen char cc+1, with z → a) so that oldPasswords[i] becomes a subsequence; else "NO".

Constraints

  • 1 ≤ n ≤ 10
  • Sum of all password lengths ≤ 2·10⁵
  • |oldPasswords[i]| ≤ |newPasswords[i]|

Example

newPasswords = ["baacbab", "accdb", "baacba"]
oldPasswords = ["abdbc", "ach", "abb"]
answer = ["YES", "NO", "YES"]
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Amazon has n items with values items[0..n-1] and m orders. The i-th order is the contiguous range [start[i], end[i]], and contributes every items[j] for start[i] ≤ j ≤ end[i] (with multiplicity) to a global multiset (so an item that lies in k orders is counted k times). For each value query[i], return the number of elements in the multiset that are strictly less than query[i]. Return the answers as an array.

Constraints

  • 1 ≤ n, m, q ≤ 10⁵
  • 1 ≤ items[i], query[i] ≤ 10⁹
  • 0 ≤ start[i] ≤ end[i] < n

Example

n = 5, items = [1, 2, 5, 4, 5], m = 3
start = [0, 0, 1], end = [1, 2, 2]
query = [2, 4]
answer = [2, 5]
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given an array cost of n item costs. You must choose a single target total T and then build packages, each containing at most 2 items, such that every built package has total cost exactly T. Each item is used in at most one package and an item with cost[i] = T may form a one-item package on its own. Return the maximum number of packages that can be built (over the best choice of T).

Constraints

  • 1 ≤ n ≤ 2·10⁵
  • 1 ≤ cost[i] ≤ 2000

Example

n = 9
cost = [4, 5, 10, 3, 1, 2, 2, 2, 3]
answer = 4
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Amazon must distribute n games (with sizes gameSize[0..n-1]) to k children using identical pen drives of capacity C. Each child receives at least 1 and at most 2 games, every game is given to exactly one child, and the total size of games for any child must not exceed C. Return the minimum capacity C that makes a valid distribution possible.

Constraints

  • 1 ≤ k ≤ n ≤ 2·10⁵, n ≤ 2k
  • 1 ≤ gameSize[i] ≤ 10⁹

Example

n = 4, gameSize = [9, 2, 4, 6], k = 3
answer = 9
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Amazon's monitoring service is comparing n processes. The i-th process has computational load process[i]. Two processes i and j are considered computationally equivalent if |process[i] - process[j]| ≤ m. Given the array process and the threshold m, return the number of unordered pairs (i, j) (with i ≠ j) of computationally equivalent processes.

Constraints

  • 1 ≤ n ≤ 2·10⁵
  • 1 ≤ process[i] ≤ 10⁸
  • 0 ≤ m ≤ 10⁸

Example

n = 4, process = [7, 10, 13, 11], m = 3
answer = 4
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Amazon has n servers; the i-th server has health health[i] and belongs to type serverType[i]. You may choose at most m distinct server types; once a type is chosen, all servers of that type are selected. The total health is the sum of health[i] over every selected server. Return the maximum possible total health.

Constraints

  • 1 ≤ m ≤ n ≤ 10⁵
  • 1 ≤ health[i] ≤ 10⁹
  • 1 ≤ serverType[i] ≤ n

Example

n = 4, health = [4, 5, 5, 6], serverType = [1, 2, 1, 2], m = 1
answer = 11
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

There are n host servers; the throughput of the i-th host is host_throughput[i]. Partition some subset of the servers into disjoint triples (each triple uses 3 distinct servers; any number of servers may be left unused). Each triple contributes the median of its three throughputs to the total. Return the maximum achievable sum of medians.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ host_throughput[i] ≤ 10⁹

Example

n = 5, host_throughput = [2, 3, 4, 5, 4]
answer = 4
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given strings userID1 (length n), userID2 (length m), and a positive integer p, the p-matching score is the number of starting indices i (with 0 ≤ i and i + (m − 1)·p < n) such that the m characters userID1[i], userID1[i+p], userID1[i+2p], …, userID1[i+(m−1)·p] form a permutation of userID2. Return the p-matching score.

Constraints

  • 1 ≤ m ≤ n ≤ 10⁶
  • 1 ≤ p ≤ 10⁶

Example

userID1 = "acaccaa", userID2 = "aac", p = 2
answer = 2
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Amazon has n delivery centers; the i-th currently holds parcels[i] parcels. Each day you must pick a positive integer d and ship exactly d parcels from every center that still has at least d parcels (centers with fewer than d parcels are skipped that day). The day fails (does not count) if no center can ship. Return the minimum number of days needed until every center is empty.

Constraints

  • 1 ≤ n ≤ 10⁶
  • 0 ≤ parcels[i] ≤ 10⁹

Example

parcels = [2, 3, 4, 3, 3]
answer = 3
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given a battery cell array charge[0..n−1] (values may be negative). You must repeatedly perform the following operation until only one cell remains: pick any index i and merge charge[i] with one of its current neighbours by adding the chosen neighbour's value into charge[i] and removing the neighbour from the array. You may also discard any cell entirely (without merging) at any time. Equivalently, you must choose a contiguous subarray of the original charge and return its sum; return the maximum achievable single-cell value.

Constraints

  • 1 ≤ n ≤ 2·10⁵
  • -10⁹ ≤ charge[i] ≤ 10⁹

Example

n = 5, charge = [-2, 4, 3, -2, 1]
answer = 9
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given an n × n matrix data and an array factor[0..n−1], where factor[i] is the maximum number of elements you may pick from row i. Choose exactly x elements in total (across all rows) so that row i contributes at most factor[i] elements. Return the maximum possible sum of the chosen elements, or -1 if it is impossible to pick x elements under the row constraints.

Constraints

  • 1 ≤ n ≤ 1000
  • 1 ≤ data[i][j] ≤ 10⁹
  • 0 ≤ factor[i] ≤ n
  • 0 ≤ x ≤ n²

Example

n = 3, data = [[6, 8, 3], [5, 10, 6], [1, 1, 5]], factor = [2, 1, 3], x = 5
answer = 30
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

There are n delivery agents; agent i already carries parcels[i] parcels. You must distribute exactly extra_parcels additional parcels (each one assigned to any agent of your choice; parcels are indivisible). Return the minimum possible value of the maximum load over all agents after distribution.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ extra_parcels ≤ 10¹⁵
  • 1 ≤ parcels[i] ≤ 10⁹

Example

n = 5, parcels = [7, 5, 1, 9, 1], extra_parcels = 25
answer = 10
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given an n x m grid of '0' / '1' pixels, the greyness of cell (i,j) = (# 1s in row i + # 1s in column j) - (# 0s in row i + # 0s in column j). Find the maximum greyness.

Constraints

  • 1 ≤ n, m ≤ 1000

Example

pixels = ["101", "001", "110"]
answer = 2
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Player passes n rounds, losing power[i] health each. Health must stay strictly positive. May use armor once on any round to reduce damage to min(armor, power[i]). Find the minimum starting health.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ armor ≤ 10⁹
  • 1 ≤ power[i] ≤ 10⁹

Example

power = [1, 2, 6, 7], armor = 5
answer = 12
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given an array data of length n. Find a permutation p[1..n] of [1..n] such that the sum Σᵢ i · data[p[i] − 1] (for i = 1..n) is maximized. Among all permutations that attain the maximum, return the lexicographically smallest one.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ data[i] ≤ 10⁹

Example

n = 3, data = [2, 1, 2]
answer = [2, 1, 3]
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Warehouses 1..n with non-decreasing warehouseCapacity. Each warehouse connects to the nearest hub at position ≥ its own. The hub at position n is fixed; for each query (hubA, hubB), place additional hubs at positions hubA and hubB. Cost of warehouse i connecting to hub at j is warehouseCapacity[j] - warehouseCapacity[i]. Sum the minimum total cost.

Constraints

  • 1 ≤ n, q ≤ 2·10⁵
  • 1 ≤ warehouseCapacity[i] ≤ 10⁹
  • 1 ≤ hubA < hubB < n

Example

warehouseCapacity = [1, 2, 4, 6, 9]
additionalHubs = [[1, 3]]
answer = [13]
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given a string productTypes of lowercase letters and integer m, count the number of split points such that the set of distinct chars shared by the prefix and the suffix has size > m.

Constraints

  • 1 ≤ |productTypes| ≤ 10⁵
  • 0 ≤ m ≤ 26

Example

productTypes = "abbcac", m = 1
answer = 2
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Initially items[] is in the cart. Process query[]: if positive, append to cart; if negative, remove the first occurrence of |x|. Return the final cart.

Constraints

  • 1 ≤ n, q ≤ 2·10⁵
  • 1 ≤ items[i] ≤ 10⁹
  • -10⁹ ≤ query[i] ≤ 10⁹, query[i] != 0

Example

items = [1, 2, 1, 2, 1], query = [-1, -1, 3, 4, -3]
answer = [2, 2, 1, 4]
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given dominos with sizes domino[] (length n), a removal sequence remove[] (permutation of [0..n-1]), and integer min_order, find the maximum number of removals k such that the longest strictly increasing subsequence over the remaining dominos is still ≥ min_order.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ domino[i] ≤ 10⁹
  • 0 ≤ remove[i] ≤ n - 1
  • 1 ≤ min_order ≤ n

Example

n = 6, domino = [1, 4, 4, 2, 5, 3], remove = [2, 1, 4, 0, 5, 3], min_order = 3
answer = 3
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

There are total_servers servers arranged in a ring (server 1 is adjacent to server total_servers). A subset of n of them, listed in servers[], must all be visited. You may start at any server in servers, and moving to an adjacent server in the ring takes 1 unit of time. Return the minimum total time required to visit every server in servers.

Constraints

  • 1 ≤ total_servers ≤ 10⁵
  • 1 ≤ n ≤ total_servers
  • 1 ≤ servers[i] ≤ total_servers

Example

total_servers = 8
servers = [2, 4, 7]
answer = 5
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given a string of digits s_id. In one operation you may pick an index i, remove the digit s_id[i], and reinsert the value min(s_id[i] + 1, 9) at any position of the (now shorter) string. You may perform any number of operations. Return the lexicographically smallest string that can be obtained.

Constraints

  • 1 ≤ |s_id| ≤ 2·10⁵

Example

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

You are given an array fruits[0..n−1]. In one operation you may pick any two indices i ≠ j such that fruits[i] ≠ fruits[j] and remove both elements from the array. You may perform any number of operations. Return the minimum possible size of the remaining array.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ fruits[i] ≤ 10⁹

Example

n = 5, fruits = [3, 3, 1, 1, 2]
answer = 1
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

There are n security centers located at integer positions center[0..n−1] on a number line, and n destinations at positions destination[0..n−1]. You must match each center to a distinct destination (a perfect bijection). The total cost of a matching is Σᵢ |center[i] − destination[match(i)]|. Return the minimum total cost over all matchings.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ center[i], destination[i] ≤ 10⁹

Example

n = 3, center = [1, 2, 2], destination = [5, 2, 4]
answer = 6
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given ratings[n] and impactFactor. Apply exactly one of: multiply a contiguous segment by impactFactor, OR divide a contiguous segment by impactFactor (floor for positive, ceil for negative). Maximize the resulting maximum-subarray sum.

Constraints

  • 1 ≤ n ≤ 10⁵
  • |ratings[i]| ≤ 10⁹

Example

n = 5, ratings = [5, -3, -3, 2, 4], impactFactor = 3
answer = 12
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

password and reference strings. For each character c, you may remove an occurrence of c from password at cost cost[c - 'a']. Goal: remove all occurrences of any character in reference. Return the minimum cost.

Constraints

  • 1 ≤ |password|, |reference| ≤ 10⁵
  • 1 ≤ cost[i] ≤ 100

Example

password = "kkkk"
reference = "k"
cost = [1,1,1,1,1,1,1,1,1,1,5,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]  # cost['k' - 'a'] = cost[10] = 5
answer = 20
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given size[n] and cost[n]. Increasing size[i] by 1 costs cost[i]. Make all sizes distinct with minimum total cost.

Constraints

  • 1 ≤ n ≤ 2·10⁵
  • 1 ≤ size[i] ≤ 10⁹
  • 1 ≤ cost[i] ≤ 10⁴

Example

n = 4, size = [2, 3, 3, 2], cost = [2, 4, 5, 1]
answer = 7
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

n piles with boxes[i] boxes; each op moves one box from any nonempty pile to any other. Find the minimum number of operations to reach the minimum possible max-min difference.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ boxes[i] ≤ 10⁹

Example

n = 4, boxes = [5, 5, 8, 7]
answer = 2
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given an array memory[0..n−1] representing the memory value of each of n chapters. You may read the chapters in any order. After reading the k-th chapter (in your chosen order), your accumulated memory equals the sum of the memory values of the first k chapters you have read. Your total memory points is the sum of these running totals after every chapter (i.e. Σₖ₌₁..ₙ (running sum after k chapters)). Return the maximum achievable total memory points.

Constraints

  • 1 ≤ n ≤ 10⁵
  • -10³ ≤ memory[i] ≤ 10³

Example

n = 3, memory = [3, 4, 5]
answer = 26
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

There are n robots placed at integer coordinates (x[i], y[i]). A robot is called idle if there exists at least one other robot directly to its left (same y, smaller x), directly to its right (same y, larger x), directly above (same x, larger y), and directly below (same x, smaller y). Return the number of idle robots.

Constraints

  • 1 ≤ n ≤ 10⁵
  • -10⁹ ≤ x[i], y[i] ≤ 10⁹

Example

x = [0, 1, 2, 0, 1, 2, 0, 1, 2]
y = [0, 0, 0, 1, 1, 1, 2, 2, 2]
answer = 1
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given values[n] and k, find both the maximum median and the minimum median over all subsequences of length k.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 0 ≤ values[i] ≤ 10⁹
  • 1 ≤ k ≤ n

Example

n = 3, values = [1, 2, 3], k = 2
answer = [2, 1] (max median, min median)
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given a palindrome of lowercase letters, return the lex-smallest palindrome that is a rearrangement of its characters.

Constraints

  • 1 ≤ |letters| ≤ 10⁸
  • All lowercase; input is a palindrome.

Example

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

Given n items with locations[i]. Op: either pick two items with different locations and ship both (one op), or pick one item and ship it (one op). Find minimum number of ops to ship all.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ locations[i] ≤ 10⁹

Example

n = 5, locations = [1, 8, 6, 7, 7]
answer = 3
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given a string command of length n over lowercase letters, an array profit[0..n−1], and an integer k. You may execute any subset of the indexed commands (skipping the others). The constraint is that within every maximal run of identical letters in command (i.e. each contiguous block of the same character) you may execute at most k of those commands. Your total profit equals the sum of profit[i] over executed indices. Return the maximum achievable profit.

Constraints

  • 1 ≤ n ≤ 2·10⁵
  • 1 ≤ profit[i] ≤ 10⁹
  • 1 ≤ k ≤ n

Example

n = 5, command = "abbba", k = 2, profit = [1, 4, 2, 10, 3]
answer = 18
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given a string productSeq over the alphabet {a, b, c, d, e, f, g}. Count the number of non-empty contiguous substrings t of productSeq such that max_freq(t) ≤ distinct(t), where max_freq(t) is the highest occurrence count of any single character in t and distinct(t) is the number of distinct characters appearing in t.

Constraints

  • 1 ≤ |productSeq| ≤ 10⁵
  • Letters from {a..g} only.

Example

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

Given cost[n] and k. Partition into exactly k contiguous nonempty parts. Cost of part [l..r] is cost[l] + cost[r]. Return [min total cost, max total cost].

Constraints

  • 1 ≤ k ≤ n ≤ 2·10⁵
  • 1 ≤ cost[i] ≤ 10⁹

Example

cost = [1, 2, 3, 2, 5], k = 3
answer = [14, 18]
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given a string genome of lowercase letters and a single lowercase character mutation. At every time step (t = 1, 2, …), every occurrence of mutation that currently has a non-mutation character immediately to its left removes that left neighbour from the string (all such removals happen simultaneously). Return the earliest time t after which no further removals occur (i.e. the total number of time steps it takes for the process to stabilise). Return 0 if no removal ever happens.

Constraints

  • 1 ≤ |genome| ≤ 10⁵
  • mutation is a lowercase letter.

Example

genome = "tamem", mutation = 'm'
answer = 2
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given machines[n] and k. Remove exactly k consecutive elements to minimize the sum of |machines[i+1] - machines[i]| over the remaining array.

Constraints

  • 1 ≤ k < n ≤ 2·10⁵
  • 1 ≤ machines[i] ≤ 10⁹

Example

machines = [3, 9, 4, 2, 16], k = 3
answer = 6
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

There are n servers; server i answers request[i] requests per second and has health health[i]. Every second the system sends a number of requests equal to the sum of request[i] over all servers that are still alive at the start of that second. In the same second the developers also pick exactly one still-alive server and reduce its health by k; a server dies as soon as its health reaches 0 or below. Once every server is dead, exactly 1 final request is sent. Choose the attack order that minimises the total number of requests sent, and return that minimum.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ request[i], health[i] ≤ 5·10³
  • 1 ≤ k ≤ 5·10³

Example

n = 2, request = [3, 4], health = [4, 6], k = 3
answer = 21
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given n closed integer intervals where interval i is [a[i], b[i]], and an integer k. You must add exactly one additional interval [a, b] (you may freely choose a and b as long as b − a ≤ k). After adding it, intervals are merged into connected components by overlap or touching. Return the minimum possible number of connected components that result.

Constraints

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

Example

intervals = [(1,5), (2,4), (6,6), (7,14), (16,19)], k = 2
answer = 2
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given an array productSize[0..n−1]. Reorder its elements into some permutation p[0..n−1]. For each prefix p[0..i] define its variation as max(p[0..i]) − min(p[0..i]). Return the minimum possible value of Σᵢ₌₀ⁿ⁻¹ variation(p[0..i]) over all permutations.

Constraints

  • 1 ≤ n ≤ 2000
  • 1 ≤ productSize[i] ≤ 10⁹

Example

n = 3, productSize = [3, 1, 2]
answer = 3
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given an array param[0..n−1]. For each i you must choose a non-negative integer secretKey[i] and compute hash[i] = secretKey[i] mod param[i]. Each hash[i] therefore lies in the range [0, param[i] − 1]. Choose the secretKey array to maximise the number of distinct values present in hash[0..n−1], and return that maximum.

Constraints

  • 1 ≤ n ≤ 2·10⁵
  • 1 ≤ param[i] ≤ 10⁹

Example

n = 3, param = [1, 2, 4]
answer = 3
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given a palindrome string productLabel. Count indices i such that deleting productLabel[i] still leaves a palindrome.

Constraints

  • 2 ≤ |productLabel| ≤ 10⁵
  • Lowercase letters only.

Example

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

You are given a binary string s of length n. A non-empty contiguous substring is called special if the number of '0' characters in it equals the square of the number of '1' characters in it (i.e. cnt0 = cnt1²). Count the number of special substrings of s.

Constraints

  • 1 ≤ |s| ≤ 10⁵

Example

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

Given match[n], find the maximum number of non-intersecting matches. Two matches (i, m[i]) and (j, m[j]) intersect iff i < j and m[i] > m[j], or i > j and m[i] < m[j].

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ match[i] ≤ n

Example

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

You are given a binary string frames of even length n. You may flip any number of bits, and you must end up with a string that can be partitioned into maximal runs of identical characters where every run has even length. First minimise the number of flips required to reach such a string; among all flip patterns that hit that minimum, return the minimum possible number of maximal runs in the resulting string.

Constraints

  • 2 ≤ n ≤ 10⁵, n even.

Example

frames = "11100110"
answer = 2  // flip index 4 → "11110000" has 2 runs
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

There are n warehouses with inventories inventory[0..n−1]. Warehouses are processed one at a time. For each warehouse, you and a co-worker dispatch in alternating turns: you go first and remove dispatch1 units, then your co-worker removes dispatch2 units, and the cycle repeats until inventory hits 0 or below. Whoever performs the final dispatch (the one that drops the inventory to ≤ 0) earns the credit for that warehouse. Your co-worker may skip their own turn — but in total, across all warehouses, they may skip at most skips turns. Choose how to spend those skips to maximise the number of warehouses for which you earn the credit, and return that maximum.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ inventory[i] ≤ 10⁹
  • 1 ≤ dispatch1, dispatch2, skips ≤ 10⁹

Example

inventory = [3, 6, 2], dispatch1 = 2, dispatch2 = 3, skips = 1
answer = 2
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Choose the maximum number of servers from powers[n] so that, when arranged in a circle, every adjacent pair (including first-last) differs by ≤ 1.

Constraints

  • 1 ≤ n ≤ 2·10⁵
  • 0 ≤ powers[i] ≤ 10⁹

Example

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

Given a permutation packageSequence[n] of [1..n]. In each pass, scan L→R; if current element equals sortedCount + 1, sort it and increment sortedCount. Find the number of passes to sort all.

Constraints

  • 1 ≤ n ≤ 10⁶

Example

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

A permutation of [0..n-1]. Swap arr[i] and arr[j] only if (arr[i] & arr[j]) == k. Find the maximum non-negative k for which the array can be sorted.

Constraints

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

Example

n = 4, arr = [0, 3, 2, 1]
answer = 1
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given n items with warehouses[i]. Op: ship 2 items from different warehouses (1 op), OR ship 1 item alone (1 op). Find minimum ops to ship all. (Same as Problem 45 — repeated under different naming.)

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ warehouses[i] ≤ 10⁹

Example

n = 5, warehouses = [2, 9, 7, 8, 8]
answer = 3
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given values[n], binary state (length n), and integer m. In each operation, pick an index where state[i] = '1', append values[i] to S, then for every "blocked-then-unblocked" rule, change one specific '0' to '1'. Maximize the lexicographic order of S of length m.

Constraints

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

requests = [[customerId, quantity, bidAmount, timestamp], ...], total inventory T. Allocate by descending bid; on tie, round-robin by ascending timestamp. Return IDs of customers who get nothing, sorted ascending.

Constraints

  • 1 ≤ n ≤ 10⁴
  • 1 ≤ customerId, quantity, bidAmount, timestamp, totalInventory ≤ 10⁸

Example

requests = [[1, 5, 5, 0], [2, 7, 8, 1], [3, 7, 5, 1], [4, 10, 3, 3]]
totalInventory = 18
answer = [4]
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given two strings primary and secondary of lowercase letters. Merge interleaving them (preserving each one's order) to form a single string with minimum number of inversions (positions where a higher letter precedes a lower one).

Constraints

  • 1 ≤ |primary|, |secondary| ≤ 1000

Example

primary = "zc", secondary = "qd"
answer = 2
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Sort bugs[n] by ascending frequency (ties broken by ascending bug code).

Constraints

  • 1 ≤ n ≤ 2·10⁵
  • 1 ≤ bugs[i] ≤ 10⁶

Example

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

t scenarios. Each has truckCapacities[n] and packageWeights[m]. Delivering a package reduces that truck's capacity to floor(cap/2). Each delivery uses a truck whose current capacity ≥ package weight. Return 1 if all packages deliverable in this scenario, else 0.

Constraints

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

Inventory quality[n]. Op: choose two values x and y; replace every x with y at cost = (number of xs). Goal: all occurrences of each quality value must be contiguous. Minimize total cost.

Constraints

  • 1 ≤ n ≤ 2·10⁵
  • -10⁹ ≤ quality[i] ≤ 10⁹

Example

n = 7, quality = [7, 7, 5, 7, 3, 5, 3]
answer = 4
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

m hubs in a ring. Travel time between adjacent hubs is transitionTime[i]. Starting at hub 1, visit requestedHubs[] in order. Minimize total travel.

Constraints

  • 1 ≤ n ≤ 2·10⁵
  • 1 ≤ m ≤ 5000
  • 1 ≤ transitionTime[i] ≤ 10⁶

Example

m = 3, n = 4, transitionTime = [5, 2, 1], requestedHubs = [1, 3, 3, 2]
answer = 4
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given affinity[n] (n even) and m rules; each rule (x, y) says "if either index x or y is chosen for a region in one step, the other must be chosen for the opposite region in the next step." Maximize total affinity assigned to regionA over alternating steps (A first).

Constraints

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

planCost[n] and featureCost[m]. X incompatible pairs (planIdx, featureIdx) (1-indexed). Find the maximum planCost[p] + featureCost[f] over valid pairs.

Constraints

  • 2 ≤ n, m ≤ 10⁵
  • 1 ≤ X ≤ min(2·10⁵, n*m - 1)
  • 1 ≤ planCost[i], featureCost[i] ≤ 10⁹
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given prices[n], integers k and d. Each op picks two indices (x, y) and a p ≤ k, then prices[x] += p, prices[y] -= p. Make max - min < d with minimum ops.

Constraints

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

Given strValue of lowercase letters. Op: pick any proper substring and sort it. Minimum ops to sort the entire string?

Constraints

  • 3 ≤ |strValue| ≤ 10⁵

Example

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

Given population[n] and binary string unit of length n. A unit at city i > 1 can be moved one step left to city i - 1 (at most once). Maximize total population covered.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ population[i] ≤ 10⁴

Example

n = 5, population = [10, 5, 8, 9, 6], unit = "01101"
answer = 27
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

n users with start_time[i]..end_time[i]. Each second a user is active contributes 1 to total usage. Find the earliest second T at which the cumulative usage reaches max_usage.

Constraints

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

String pipeline; character failedService. Each second, every occurrence of failedService removes the character immediately before it. Find the time when no further removals happen.

Constraints

  • 1 ≤ |pipeline| ≤ 2·10⁵

Example

pipeline = "database", failedService = 'a'
answer = 2
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Group n servers by security grade. Each group contains servers of one grade; sizes of any two groups differ by at most 1. Minimize the number of groups.

Constraints

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

Shopper visits a shop with n items, cost cost[], money m. Buys items left-to-right; each subsequent purchase of item i costs (k_i)·cost[i] where k_i is the number of times this item has been bought so far + 1. Loop around when reaching the end. Return total items bought.

Constraints

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

Given max_products and an array tasks[n]. Each day, tasks[i] modifies inventory; if tasks[i] > 0, deliver; if tasks[i] < 0, dispatch; if tasks[i] == 0, inspect (inventory must be ≥ 0). Each morning the manager can emergency-add any number of products at $1 each. Find minimum total emergency products to keep inspections passing, OR -1 if impossible.

Constraints

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

Given memory[n] (n even). Split into n/2 primary and n/2 backup such that each primary has a backup with memory[B] <= memory[P]. Maximize sum of memory[P] over all primaries.

Constraints

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

n VM types with stocks vmStock[]. Each of m customers takes from the type with highest current availability; revenue from that customer = min_nonzero(current stocks) + max(current stocks). Compute total revenue after serving all customers.

Constraints

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

Given cost[m]. Op: pick (x, y) where cost[x] % cost[y] == 0 and set cost[x] = cost[y]. Minimize total cost.

Constraints

  • 1 ≤ m ≤ 2·10⁶
  • 1 ≤ cost[i] ≤ 2·10⁸

Example

m = 5, cost = [3, 6, 2, 6, 25]
answer = 17
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Grid expansion: start (p1, q1), end (p2, q2). Each step: add a row (vertical, top) or add a column (horizontal, right). Each added "frontier" gets exactly one filled cell. Count distinct final fillings, mod 998244353.

Constraints

  • 1 ≤ p1 ≤ p2 ≤ 1000
  • 1 ≤ q1 ≤ q2 ≤ 1000

Example

p1 = 1, q1 = 1, p2 = 2, q2 = 2
answer = 3
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given customer_rating[n], integers k and m. Each op increases one rating by 1 (max k ops total). Maximize the Bitwise AND of any m-sized subset of the modified array.

Constraints

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

Given power[n]. You can add x_l ≥ 0 to each contiguous segment (different x per chosen segment). Make power non-decreasing; minimize total x added.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ power[i] ≤ 10⁹

Example

n = 5, power = [3, 4, 1, 6, 2]
answer = 7
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

requestLogs[m] = [[skillId, timeStamp], ...]. For each queryTime[i], count skills NOT receiving any request in [queryTime - timeWindow, queryTime].

Constraints

  • 1 ≤ numSkills, m, q ≤ 10⁵
  • 1 ≤ requestLogs[i][0] ≤ numSkills
  • 1 ≤ requestLogs[i][1], queryTimes[i], timeWindow ≤ 10⁵
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Single truck of capacity T. List of packages weights[]. Each delivery uses the truck for one package whose weight ≤ current capacity; after delivery T = floor(T / 2). Return total number of packages deliverable using one truck, maximizing it.

Constraints

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

Amazon Fresh is planning a delivery route. The delivery area is a 2D grid where 1 is an accessible cell, 0 is blocked (no road), and 9 is the order destination. The truck starts at the top-left corner (always accessible) and may move up / down / left / right. Return the minimum number of steps to reach the cell containing 9, or -1 if unreachable.

Constraints

  • 1 ≤ rows, columns ≤ 10³
  • Cell values are in {0, 1, 9}; area[0][0] is always accessible.
Example:
area = [[1, 0, 0],
 [1, 0, 0],
 [1, 9, 1]]
minDistance(area) = 3
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Numbers are encrypted using a Pascal-Triangle-style scheme. Given an initial array numbers[] of digits (each in [0, 9]), repeatedly replace the array with the array of sums of adjacent elements modulo 10 (i.e., keep only the rightmost digit of each sum). Repeat until exactly 2 digits remain. Return the resulting 2-digit string (with leading zero if needed).

Constraints

  • 2 ≤ numbers.length ≤ 5 × 10³
  • 0 ≤ numbers[i] ≤ 9
Example:
numbers = [4, 5, 6, 7]
[4,5,6,7] -> [9,11,13] -> mod10 -> [9,1,3]
[9,1,3] -> [10,4] -> mod10 -> [0,4]
findNumber([4,5,6,7]) = "04"
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Amazon stores binary numbers as strings of '0', '1', and '!', where '!' is an unknown character that can be replaced with either '0' or '1'. After replacement, every subsequence "01" contributes x errors and every subsequence "10" contributes y errors. Return the minimum total errors achievable, modulo 10⁹ + 7.

Constraints

  • 1 ≤ |errorString| ≤ 10⁵
  • 0 ≤ x, y ≤ 10⁹
  • errorString contains only '0', '1', '!'.
Example:
errorString = "!!!!!!!", x = 23, y = 47
getMinErrors(errorString, x, y) = 0
(replace all '!' with '0' or all with '1' -> no "01" or "10" subsequence)
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

A defective pan balance over-reads one side by a fixed amount wt. A pair of parcels (i, j) is "balanced" iff |weight[i] - weight[j]| == wt. Given weight[n] and wt, count the number of valid pairs. (One parcel cannot appear in two pairs; we count unordered pairs (i, j).) Return the count modulo 10⁹ + 7.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ weight[i], wt ≤ 10⁹
Example:
weight = [4, 5, 5, 4, 2, 5, 3, 2, 3], wt = 1
countBalancedPairs(weight, 1) = 11
(every (4,5), (2,3), (3,2), (5,4) index-pair with |diff|==1)
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

A student has already answered answered[i] questions in subject i and needs at least needed[i] to pass it. The student can answer q more questions total, distributing them across subjects however they like. Return the maximum number of subjects that can be passed.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 0 ≤ answered[i], needed[i], q ≤ 10⁹
Example:
answered = [24, 27, 0], needed = [51, 52, 100], q = 100
gap = [27, 25, 100], sort -> [25, 27, 100]
take 25 + 27 = 52 ≤ 100 (pass 2); +100 = 152 > 100 (stop)
findMaximumNum(answered, needed, q) = 2
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given an array stocksProfit[n] and an integer target, count the number of distinct value pairs (a, b) (with a ≤ b) such that some indices i < j give stocksProfit[i] + stocksProfit[j] == target. Pairs are de-duplicated by value, not by index. If a == b, the value must appear at least twice in the array.

Constraints

  • 1 ≤ n ≤ 5 × 10⁵
  • 0 ≤ stocksProfit[i] ≤ 10⁹
  • 0 ≤ target ≤ 5 × 10⁹
Example:
stocksProfit = [6, 6, 3, 9, 3, 5, 1], target = 12
distinct value pairs summing to 12: (3, 9) and (6, 6)
getDistinctPairs(stocksProfit, target) = 2
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given a customer password c and a system-generated password s, count the number of subsequences of c that are lexicographically greater than s. A sequence x is lex greater than y iff either at the first differing position x[i] > y[i], or |x| > |y| and y is a prefix of x. Return the count modulo 10⁹ + 7.

Constraints

  • 1 ≤ |c| ≤ 10⁵
  • 1 ≤ |s| ≤ 100
  • c and s consist of lowercase English letters.
Example:
c = "bab", s = "ab"
subsequences > s: "b", "ba", "bb", "bab", "b" -> 5
countSecurePasswordVariations(c, s) = 5
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

SDE II Amazon Shopping is running a reward collection event for its customers. There are n customers and the i-th customer has collected initialRewards[i] points so far. One final tournament is to take place where: The champion earns n additional points The second place earns n - 1 points The third place earns n - 2 points … and the last place earns 1 point Given an integer array initialRewards of length n, representing the initial reward points of the customers before the final tournament: Find the number of customers i (1 ≤ i ≤ n) such that, if the i-th customer wins the final tournament, they would have the highest total points. Note - The total points = initialRewards[i] + n (if they win). Other customers also get points in the tournament depending on their ranks (from n - 1 to 1). You must check if the i-th customer, upon winning, ends up with the highest total score, regardless of how others place.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 0 ≤ initialRewards[i] ≤ 10⁵
  • Complete constraints added on 06-18-2025

Example 1

Input:

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

Output:

2

Explanation: If the 1st participant wins the final showndown, their total scores would be: 1 + 3 = 4, but this is not the highest possible scores in this scenairo. For example, if the 3rd participant with an initial earned points of 4 comes 2nd, then they would achieve a total of: 4 + 2 = 6 scores which is higher than 1st participant scores. If the 2nd participant wins the final showdown, their total points would be: 3 + 3 = 6, and this is the highest total scores in this situation. Even if the 3rd participant with an initial earned points of 4 comes 2nd, then they would achieve a total of: 4 + 2 = 6 scores which is not greater than 2nd participant scores. If the 3rd participant wins the final showdown, their total scores would be: 4 + 3 = 7, and this is the highest total scores, as there are no other participants that can achieve the total score of 7 in this case. Thus, the participants 2 and 3 are the ones such that, if they win the final showdown, they would have the highest total scores. We return 2 as the output

Example 2

Input:

initialRewards = [5, 7, 9, 11]
n = 4

Output:

1

Explanation: Only the 4th participant is the one who, if they secure victory in the final round, would achieve the highest overall score.

Example 3

Input:

initialRewards = [8, 10, 9]
n = 3

Output:

2

Explanation:

If the 2nd customer wins the final tournament, their total points would be 10 + 3 = 13, the highest possible. If the 3rd customer wins, they would get 9 + 3 = 12. Even if the 2nd customer places 2nd with 10 + 2 = 12, they don't exceed the leader. So customers 2 and 3 are the possible winners → answer is 2.

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

You have servers servers numbered 0..servers-1, all initially free. The i-th request (0-indexed) arrives at time i and lasts requests[i] seconds. When a request arrives, the lowest-indexed free server takes it; if none is free, the server that becomes free first takes it (ties broken by lowest index). Return the array of server ids assigned to each request.

Constraints

(see source image for exact bounds; standard variant of LC 1882)

Example 1

Input:

servers = 5
requests = [3, 1, 0, 2, 1]

Output:

[0, 1, 0, 2, 1]

Explanation:

(see source for details)

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

SDE II The team at a TomTom International factory has been assigned a critical optimization task aimed at improving the efficiency of packing a set of boxes, each labeled with a unique ID. These boxes are initially arranged in a single row from left to right, where the ID of the i-th box is represented by the string s_id, which consists of digits ranging from 0 to 9, inclusive. To streamline the packing process, the team has been granted the ability to perform a specific operation an arbitrary number of times, including zero times if necessary. The operation is defined as follows: The team can choose any index within the string s_id and remove the digit at that position. After removing the selected digit, the team can insert a new box with an updated ID. The new ID is determined by computing min(s_id[i] + 1, 9), ensuring that the new ID does not exceed 9. Given the initial arrangement of boxes represented by the string s_id, the goal is to determine the lexicographically minimal string that can be achieved by applying the allowed operations optimally. Clarification on Lexicographic Order: A string X is considered lexicographically smaller than another string Y of the same length if and only if, at the first position where X and Y differ, the corresponding digit in X is smaller than the corresponding digit in Y. Objective: Find and return the lexicographically smallest possible string that can be formed by performing the given operation any number of times.

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

The developers at Amazon want to perform a reliability drill on some servers. There are n servers where the ith server can serve request[i] number of requests and has an initial health of health[i] units. Each second, the developers send the maximum possible number of requests that can be served by all the available servers. With the request, the developers can also send a virus to one of the servers that can decrease the health of a particular server by k units. The developers can choose the server where the virus should be sent. A server goes down when its health is less than or equal to 0. After all the servers are down, the developers must send one more request to conclude the failure of the application. Find the minimum total number of requests that the developers must use to bring all the servers down. Function Description Complete the function minimumRequests in the editor. minimumRequests has the following parameters:

    1. int[] request: an array of integers representing the number of requests each server can serve
    1. int[] health: an array of integers representing the initial health of each server
    1. int k: an integer representing the health decrease caused by the virus Returns int: the minimum total number of requests to bring all the servers down

Constraints

N/A

Example 1

Input:

request = [3, 4]
health = [4, 6]
k = 3

Output:

21

Explanation: The minimum number of requests required is 21. Explanation image was added on 06-13-2025

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

Amazon Books is a retail store that sells the newly launched novel "The Story of Amazon". The novel is divided into volumes numbered from 1 to n and unfortunately, all the volumes are currently out of stock. The Amazon team announced that starting today, they will bring exactly one volume of "The Story of Amazon" in stock each of the next n days. On the nth day, all volumes will be there. Being an impatient bookworm, each day you will purchase the maximum number of volumes you can such that: You have not purchased the volume before. You already own all its direct prior volumes. Note: For the ith volume of the novel, all the volumes such that j the volume numbers in ascending order if you purchased some volumes on the ith day the single element -1 if you did not purchase any book Function Description Complete the function buyVolumes in the editor below. buyVolumes has the following parameter: int volumes[n]: an array of integers where the ith integer denotes the volume that is in stock on the ith day Returns int[n][n]: a 2d array of integers where the ith array denotes the volumes purchased on the ith day

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ volumes[i] ≤ n
  • Elements in volumes are distinct.

Example 1

Input:

volumes = [2, 1, 4, 3]

Output:

[[-1], [1, 2], [-1], [3, 4]]

Explanation: Initially, all volumes are out of stock T~T On the first day, Volume No.2 becomes available. Since you don't own its prequel (Volume 1) yet, you will not purchase it. The answer for the first day is [-1]. On the second day, Volume N0.1 becomes available. Now, you can puchase both vol.1 and vol.2 together. The answer for the second day is [1, 2] On the third day, Volume No.4 becomes available. Since you do not have one of its prequels (Vol.3) yet, you will not buy Vol.4. The answer for the third day is [-1]. On the fourth day, Volume No.3 becomes available. Now, you can purchase both Vol.3 and Vol.4. The answer for the fourth day is [3, 4]. The final answer is [[-1], [1, 2],[-1], [3, 4]].

Example 2

Input:

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

Output:

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

Explanation:

  • Day 1, Volume 1 is released. Purchase volume 1. answer[0] = [1]
  • Day 2, Volume 4 is released. No volumes are purchased since you do not own all volumes 1 and 3. answer[1] = [-1]
  • Day 3, Volume 3 is released. No volumes are purchased since you do not own volume 2. answer[2] = [-1]
  • Day 4, Volume 2 is released. Purchase all three volumes. answer[3] = [2, 3, 4]
  • Day 5, Volume 5 is released. Purchase volume 5. answer[4] = [5]

Example 3

Input:

volumes = [1, 2, 3]

Output:

[[1], [2], [3]]

Explanation: Day 1, Volume 1 is released. Purchase volume 1. Day 2, Volume 2 is released. Purchase volume 2. Day 3, Volume 3 is released. Purchase volume 3.

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

Given an array arr of size n and pairs of size m * 2, where each pair represents the starting and ending index of a subarray, we need to calculate the beauty of the array. The process of calculating the beauty involves creating a beautiful array by processing each pair and appending the subarray defined by the pair to the beautiful array. After processing all pairs, we need to return the summation of the count of values exactly lesser than the values at the unused indexes in the original array. Function Description Complete the function calculateBeautyValues in the editor. calculateBeautyValues has the following parameters:

    1. int arr[n]: an array of integers
    1. int pairs[m][2]: an array of pairs representing subarray indexes Returns int: the sum of counts of values less than the values at unused indexes
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given two lists: price[]: A list of integers representing the prices of different stocks. futurePrice[]: A list of integers representing the future prices of those stocks. principle: An integer representing the amount of money you have available to invest. You can buy as many stocks as you want, but the total cost of the stocks you buy must not exceed your principle. Task: Write a function that calculates the maximum profit you can make by buying stocks, where: The profit for each stock is calculated as the difference between its futurePrice and price (i.e., futurePrice[i] - price[i]). You can buy a stock only if its price is less than or equal to the available principle. Constraints

) You can buy any number of stocks, as long as the total price of the selected stocks is less than or equal to principle. If you can't buy any stock (because all stock prices exceed the principle), the maximum profit is 0. The 1010th thank you is being carried by USPS to spike!

Constraints

See above

Example 1

Input:

price = [10, 50, 30, 40, 70]
futurePrice = [100, 40, 50, 30, 90]
principle = 100

Output:

110

Explanation:

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

Imagine you're a seller on Amazon, specializing in eco-friendly products. Each of your items is rated by customers based on its quality and environmental impact. The overall qualityScore of your products is determined by the maximum possible sum of consecutive ratings. To improve the qualityScore of your products and attract more customers, you are given with an integer impactFactor and the following two strategies: Amplify Ratings: Select a contiguous segment of ratings and amplify them by multiplying each rating in that range by impactFactor. Adjust Ratings: Select a contiguous segment of ratings and adjust them by dividing each rating in that range by impactFactor Your task is to determine the maximum possible qualityScore for your eco-friendly products after applying exactly one of these strategies. Note: When applying the second strategy i.e., Adjust Ratings; For dividing positive ratings, floor the division result, and for dividing negative ratings, use the ceiling value of the division result, Example: Given ratings = [4, -5, 5, -7, 1], and impactFactor = 2. If we choose to apply the second strategy with segment [2, 5] (Assuming 1-based indexing) then, modified ratings: [4, ceil(-5/2), floor(5/2 [I think it should be 5/2 instead of S / 2], ceil(-7/2), floor(1/2)] = [4, -2, 2, -3, 0]. Note that the ceil(-7/2) = -3 and floor(5/2) = 2, Given an array of ratings of size n and an integer impactFactor, determine the maximum possible qualityScore i.e., maximum possible sum of consecutive ratings by optimally selecting exactly one of the strategies to modify the ratings. Function Description Complete the function calculateMaxQualityScore in the editor below calculateMaxQualityScore has the following parameters:

  • int impactFactor: the value used in the strategies to amplify or adjust ratings.
  • int ratings[n]: an array representing the ratings of eco-friendly products Returns long: the maximum possible qualityScore of your eco-friendly products after applying exactly one of the strategies. Possible solution hint -> Basically, if the array is not entirely negative, find the max sum subarray and multiply it by the factor. If the array is entirely negative, find the single largest negative number and divide it by the factor. Hello spike! Thanks for carrying~

Constraints

  • 1 ≤ n ≤ 2 * 10⁵
  • 1 ≤ impactFactor ≤ 10⁴
  • -10⁵ ≤ ratings[i] ≤ 10⁵

Example 1

Input:

impactFactor = 2
ratings = [5, -3, -3, 2, 4]

Output:

12

Explanation: Let's try both the strategies with different contiguous ranges to get the maximum qualityScore: If we perform the first strategy on the subsegment [4, 5] (1-based indexing), we get the ratings = [5, -3, -3, 4, 8] with a qualityScore of 12, which is the maximum qualityScore. Hence, the answer is 12.

Example 2

Input:

impactFactor = 1
ratings = [-2, 3, -3, -1]

Output:

3

Explanation: Since impactFactor = 1, applying any strategy will not change the ratings. The initial qualityScore is the maximum sum of consecutive ratings, which is 3. Note - The test cases and constraints are slightly different between the two sources I found. Example 1 and constraints are from source 1, while example 2 is from source 2.

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

You work at a company that has 5 offices, each with a distinct salary level and a priority ranking from lowest to highest as follows: Office A ($1)<OfficeB($10)< Office C ($100)<OfficeD($1,000)< Office E($ 10,000). Your work schedule is represented by a string, where each character corresponds to an office (e.g., 'D' for Office D) you work on the ith day. Your salary is calculated based on the following rule: Salary Calculation Rules: If you work in an office and no higher-priority office appears after it in the sequence, you add its salary to your total salary. If you work in an office and a higher-priority office appears later in the sequence, you subtract its salary from your total salary. The company allows you to change the office you work in, on any one day to maximise your total salary. Your task is to determine the maximum possible salary after making at most one such change. Input Format The first and only line contains a string S representing the sequence offices you worked in. Output Format Print the max salary you can get after changing at most one office to another office.

Example 1

Input:

schedule = "ABCDEEDCBA"

Output:

31000

Explanation: Not found for this time ↔. Lets make a wish to find it in the near future If you happen to know about it you are more than welcome to let us know. Thank you so much for carrying!

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

You are given a list of packets of varying sizes and there are n channels. Each of the n channel must have a single packet Each packet can only be on a single channel The quality of a channel is described as the median of the packet sizes on that channel. The total quality is defined as sum of the quality of all channels (round to integer in case of float). Given the packet sizes and num of channels, find the maximum quality. Function Description Complete the function calculateMedianSum in the editor. calculateMedianSum has the following parameters:

  • int[] packets: an array of integers
  • int n: the number of channels Returns int: the sum of the medians of each channel

Constraints

  • 1 ≤ n ≤ packets.length ≤ 10⁵
  • 1 ≤ packets[i] ≤ 10⁹

Example 1

Input:

packets = [1, 2, 3, 4, 5]
n = 2

Output:

8

Explanation: If packet {1, 2, 3, 4} is sent to channel 1, the median of that channel would be 2.5 If packet {5} is sent to channel 2, its median would be 5 Max total quality is 2.5 + 5 = 7.5 ~ 8

Example 2

Input:

packets = [5, 2, 2, 1, 5, 3]
n = 2

Output:

7

Explanation: channel 1 -> {2, 2, 1, 3,}, median = 2 channel 2 -> {5, 5}, median = 5 total quality 2 + 5 = 7

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

Giving position of trucks and they are always moving towards end station as it is a gas station. Given a second array indicating extra gas station position in 1-indexing. Calculate the total distance travelled by all the trucks. Example: Given trucks at positions [0,2,5,9,12,18] and extra gas stations at positions [[2,5],[3]], the answer to be returned is [12,18]. The solution can be solved in O(n²) time complexity with one for loop for traversing gas station array and a second loop to calculate total distance travelled. However, there are test cases where this approach may not be optimal. Function Description Complete the function calculateTotalDistanceTravelled in the editor. calculateTotalDistanceTravelled has the following parameters:

    1. int[] trucks: an array of integers indicating the initial positions of the trucks
    1. int[][] extraGasStations: a 2D array of integers indicating the positions of extra gas stations Returns int[]: an array of integers indicating the total distance travelled by all the trucks
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Trucks dispatch packages in a city. There are n trucks numbered 0, 1, ..., n - 1 used for dispatching goods. Assuming the trucks are parked along the x-coordinate axis, the coordinates of these trucks can be represented as a non-decreasing array called position, where the truck numbered i is parked at position[i]. Each truck can move towards increasing positions of x-coordinates only. At the start of the day, each truck is refuelled. There is a gas station at the position of truck number n - 1, i.e., at position[n - 1], and all other trucks can travel to this position for refuelling. The total distance travelled is the sum of distances travelled by each truck to reach the last x-coordinate position. Thus, the total distance is: (position[n - 1] - position[0]) + (position[n - 1] - position[1]) + ... + (position[n - 1] - position[n - 1]) Two additional gas stations are located at the positions of two trucks, positions a and b. Treat a and b as 1-based indexes into the position array. Given q queries of the form (a, b) where a < b, find the total distance travelled by all the trucks to refuel their tanks. Assume additional gas stations are installed at position[a - 1] and position[b - 1] for each query, and that each truck stops at the nearest gas station going in the forward direction (increasing position). Note that each query is independent, and there is always a gas station at the last position. Function Description Complete the function calculateTruckDistanceAfterRefueling in the editor. calculateTruckDistanceAfterRefueling has the following parameters:

  • int[] position: an array of integers representing the positions of trucks
  • int[][] extraGasStations: a 2D array of integers where each element extraGasStations[i] contains two integers a and b representing the 1-based indexes of the positions where extra gas stations are installed for the ith query Returns long integer: the total distance travelled by all the trucks after refueling at the nearest gas station for each query

Constraints

:P

Example 1

Input:

position = [3, 6, 10, 15, 20]
extraGasStations = [[2, 4]]

Output:

8

Explanation: There are n = 5 trucks, and their positions are position = [3, 6, 10, 15, 20]. There is q = 1 query with extra gas stations at extraGasStations = [[2, 4]]. Once extra gas stations are installed at position[2 - 1] = 6 and position[4 - 1] = 15:

  • 0th truck will move towards x = 6.
  • 1st truck will not move since there is already a gas station installed.
  • 2nd truck will move towards x = 15. Recall that trucks can move in increasing x-coordinate/position only.
  • 3rd truck will not move since there is already a gas station installed.
  • 4th truck will not move since there is already a gas station installed. Total distance travelled: (6 - 3) + (6 - 6) + (15 - 10) + (15 - 15) + (20 - 20) = 3 + 0 + 5 + 0 + 0 = 8.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

The supply chain manager at one of Amazon's warehouses wants to measure the efficiency of the way parcels are shipped. The volume of each parcel is represented in the array parcelWeights. Each day, the first and last parcels in the array parcelWeights are shipped until all of them are dispatched. The manager comes up with metrics to calculate warehouse efficiency. Each day before shipping, any parcel in the warehouse is chosen and its volume is added to the sum of total efficiency. A parcel can only be chosen once. Given the array parcelWeights, find the maximum possible efficiency of the warehouse.

Constraints

1≤n≤2x10⁵ 0≤parcle_weights[i]≤10⁹

Example 1

Input:

parcelWeights = [4, 4, 8, 5, 3, 2]

Output:

17

Explanation:

Example 2

Input:

parcelWeights = [2,1,8,5,6,2,4]

Output:

23

Explanation: In case 1, the order of picked parcels would produce an answer of 4 + 2 + 8 + 5 = 19, which is incorrect. The correct selection of parcels would be in scenario 2, where the answer will be 4 + 6 + 8 + 5 = 23.

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

Amazon recently conducted interviews where the candidates were asked to sort the permutation p of length n. Then the ith candidate sorted the permutation in moves[i] moves. To verify the result once more, the interviewer wants to find if it is possible to sort the given permutation in the given number of moves. Given the original permutation array p and the number of moves made by each of the q candidates, find whether you can sort the permutation p by performing exactly moves[i] moves. In one move, you swap the value at any two distinct indexes. Return the answer as a binary string of length q. The value at the ith index should be 1 if it is possible to sort the permutation in exactly moves[i] moves, otherwise the value should be 0. Note: A permutation is a sequence of n distinct integers such that each integer between [1, n] appears exactly once. For example, [1, 2, 3, 4] is a permutation of size 4, but [1, 3, 4, 5] or [1, 2, 2, 4] is not.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ q ≤ 10⁵
  • 1 ≤ moves[i] ≤ 10⁹
  • It is guaranteed that p forms a permutation.

Example 1

Input:

p = [2, 3, 1, 4]
moves = [2, 3]

Output:

"10"

Explanation: For the first candidate with 2 moves:

  • Swap index 0 and 2 (Permutation becomes [1, 3, 2, 4])
  • Swap index 1 and 2 (Permutation becomes [1, 2, 3, 4]) The permutation is sorted in exactly 2 moves, so the answer is 1 for the first candidate. For the second candidate with 3 moves, it is not possible to sort the permutation in exactly 3 moves, so the answer is 0 for the second candidate. The final answer is "10".

Example 2

Input:

p = [4, 5, 1, 3, 2]
moves = [1, 2, 3]

Output:

"011"

Explanation: Outputs from these two examples are educated guesses :) It is not possible to sort the permutation in exactly 1 move, so the answer is 0 for the first candidate. For the second candidate with 2 moves:

  • Swap index 0 and 4 (Permutation becomes [2, 5, 1, 3, 4])
  • Swap index 1 and 2 (Permutation becomes [2, 1, 5, 3, 4]) The permutation is not sorted, so the answer is 0 for the second candidate. For the third candidate with 3 moves, it is possible to sort the permutation, so the answer is 1 for the third candidate. The final answer is "011".
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Amazon has recently established n distribution centers in a new location. They want to set up 2 warehouses to serve these distribution centers. Note that the centers and warehouses are all built along a straight line. A distribution center has its demands met by the warehouse that is closest to it. A logistics team wants to choose the location of the warehouses such that the sum of the distances of the distribution centers to their closest warehouses is minimized. Given an array dist_centers, that represent the positions of the distribution centers, return the minimum sum of distances to their closest warehouses if the warehouses are positioned optimally. Function Description Complete the function minSumDistancesToWarehouses in the editor. minSumDistancesToWarehouses has the following parameter:

  • int[] dist_centers: an array of integers representing the positions of the distribution centers Returns int: the minimum sum of distances to their closest warehouses
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

SDE II A prominent media company (AMZ MGM) has partnered with select theaters to showcase exclusive video content, including feature films, episodic series, live performances, and more. You are given an integer n, representing the number of scheduled screenings. Each screening has a start time, duration, and expected audience size, which are provided as integer arrays start, duration, and volume, respectively. Your task is to determine the highest possible total audience size while ensuring that no two selected screenings overlap. Two screenings are considered non-overlapping if one fully concludes before the next one begins. Function Description Complete the function cinemaShows in the editor below. cinemaShows has the following parameter(s):

  • int start[n]: an integer array denoting the start times of each show
  • int duration[n]: an integer array denoting the durations of each show
  • int volume[n]: an integer array denoting the volumes of each show Returns int: an integer denoting the maximum possible volume that can be received

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ start[i] ≤ 10⁹
  • 1 ≤ duration[i] ≤ 10⁹
  • 1 ≤ volume[i] ≤ 10³

Example 1

Input:

start = [10, 5, 15, 18, 30]
duration = [20, 12, 20, 35, 35]
volume = [50, 51, 20, 25, 10]

Output:

76

Explanation:

Example 2

Input:

start = [1, 2, 4]
duration = [2, 2, 1]
volume = [1, 2, 3]

Output:

4

Explanation: Will udpate once find more reliable resources :) As always

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

A circular route has n stops numbered from 0 to n - 1. The array distances has length n, where distances[i] is the distance from stop i to stop (i + 1) % n. You are given several route queries. Each query [start, end] asks for the shorter of the two possible distances between those stops on the circle. Return the sum of the shortest distances over all queries.

Constraints

Stops are zero-indexed. Each query contains two valid stop indices. No numeric limits were provided in the source; an efficient solution should precompute prefix sums around the circle.

Example 1

Input:

distances = [1,2,3,4]
queries = [[0,1],[1,3],[3,0]]

Output:

10

Explanation: The shortest distances are 1, 5, and 4, so the total is 10.

Example 2

Input:

distances = [7,10,1,12]
queries = [[0,2],[2,1]]

Output:

23

Explanation: For 0 to 2, the counter-clockwise route is shorter with distance 13. For 2 to 1, the opposite direction has distance 10.

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

Data Scientists at Amazon are working on cleansing a machine learning dataset. The dataset is represented as a string dataset consisting of an even number of lowercase English letters. The goal is to clean the dataset efficiently by performing specific operations. Here's how the operations work:

  • In each operation, two characters from the dataset are selected and removed.
  • Each operation has an associated cost:
  • x: the cost of removing two identical characters.
  • y: the cost of removing two different characters. The task is to determine the optimal strategy that minimizes the total cost to completely clean up the dataset. In other words, find the minimum cost required to remove all characters and make the dataset empty. Function Description Complete the function cleanupDataset in the editor. cleanupDataset has the following parameters:
  • String dataset: a string that denotes a machine learning dataset
  • int x: the cost of operation when the removed characters are equal
  • int y: the cost of operation when the removed characters are unequal Returns int: the minimum cost to clean up the dataset or make the string empty Many Thankssss to da best --> jake !!

Constraints

  • 2 ≤ |dataset| ≤ 10⁵
  • |dataset| is even
  • 1 ≤ x, y ≤ 10⁴

Example 1

Input:

dataset = "aaabca"
x = 3
y = 2

Output:

7

Explanation: In the first operation, the first and second characters are deleted from the dataset, resulting in dataset = "abca". The cost of this operation is x = 3 because both removed characters are equal (also 'a'). In the next operation, the first and third characters are deleted, making dataset = "ba". The cost of this operation is y = 2 because the removed characters are not equal. In the final operation, the remaining two characters are deleted, making the dataset an empty string. The cost of this operation is y = 2 because the removed characters are not equal. Hence, the total cost is 3 + 2 + 2 = 7.

Example 2

Input:

dataset = "ouio"
x = 2
y = 4

Output:

6

Explanation: Operation 1 - Action: removed the first and last characters of the dataset, resulting in the string dataset = "ui". Cost: x = 2 (since both removals, 'o' and 'o' are the same) Operation 2 - Action: delete the remaining characters of "ui", making dataset an empty string. Cost: y = 4 (since the removed characters, 'u' and 'i' are diff) Total cost --> x + y = 2 + 4 = 6

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

The Amazon distribution center consists of arrays of products, each possessing unique attributes. The task at hand is to compute the beauty of these product arrays, with the goal of achieving an efficient selection process. More specifically, there are arrays of products, and each array corresponds to a list of attributes. The beauty of a subarray B = [products[l], products[l+1], ..., products[r]] is quantified by counting the indices i that satisfy these conditions: l ≤ i ≤ r for every index j such that i products[j] An array B is a subarray of an array A if B can be obtained from A by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. In particular, an array is a subarray of itself. The beautiness of the entire array of products is determined by the sum of beauty values across all subarrays of a given size k. Given an array products of size n and an integer k. Compute the total beautiness of the array of products. Function Description Complete the function computeBeauty in the editor. computeBeauty has the following parameters:

    1. int[] products: an array of integers representing the products
    1. int k: the size of the subarray Returns int: the total beautiness of the array of products Endlessly grateful to the amazing friend for their help!

Example 1

Input:

products = [3, 6, 2, 9, 4, 1]
k = 3

Output:

8

Explanation: So, the beauty of the array numbers is 2 + 1 + 2 + 3 = 8.

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

Amazon's software team utilizes several algorithms to maintain data integrity, one of which targets the encoding of symmetrical names. Symmetrical names are unique in that they read identically in both directions, similar to palindromes in language parlance. The chief aim of the algorithm is to rearrange the characters in the original symmetrical name according to these criteria: The rearranged name is a reshuffled version of the original symmetrical name. The restructured name should be symmetrical as well. This restructured name should be lexicographically smallest among all its symmetric permutations. Given an initial symmetrical name that contains only lowercase English characters, compute the encoded name. A string is considered to be lexicographically smaller than the string t of the same length if the first character in s that differs from that in t is smaller. For example, "abcd" is lexicographically smaller than "abdc" but larger than "abaa". Note that the output encoded name could match the original name if it's already the smallest lexicographically. Function Description Complete the function computeEncodedProductName in the editor. computeEncodedProductName has the following parameter:

  • string nameString: the initial symmetrical string name. Returns string: the encoded nameString

Constraints

  • 1 ≤ |nameString| ≤ 105
  • nameString consists of lowercase English letters only.
  • nameString is a palindrome.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given A String Containing Integers, A Good String Is One Not Containing A Subseq

Example 1

Input:

s = "111101110100"

Output:

2

Explanation: We convert the 0s to 1s in Position 5 andnd 9 - "1111111111100"

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

You are given an undirected graph with n nodes and a list of edges. Each edge connects two nodes in the graph. Return the number of connected components in the graph. A connected component is a maximal group of nodes where every pair of nodes is connected by some path. Function Description Complete the function countConnectedComponents in the editor. countConnectedComponents has the following parameters:

  • int n: the number of nodes, labeled from 0 to n - 1
  • int edges[][]: an array where each element [u, v] represents an undirected edge between nodes u and v Returns int: the number of connected components in the graph

Constraints

  • Nodes are labeled from 0 to n - 1.
  • The graph is undirected.
  • The input edges are valid node pairs.

Example 1

Input:

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

Output:

2

Explanation: Nodes 0, 1, and 2 form one connected component. Nodes 3 and 4 form another connected component. Therefore, there are 2 connected components.

Example 2

Input:

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

Output:

2

Explanation: The cycle among nodes 0, 1, and 2 is still one connected component. Nodes 3 and 4 form the second component.

Example 3

Input:

n = 4
edges = []

Output:

4

Explanation: With no edges, every node is isolated, so each node is its own connected component.

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

Weak passwords are likely to be hacked and misused. Due to this, developers at Amazon regularly come up with new algorithms to check the health of user passwords. A new algorithm estimates the variability of a password as the number of distinct password strings that can be obtained by reversing any one substring of the original password. Given the original password that consists of lowercase English characters, find its variability. Note: A substring is a contiguous sequence of characters within a string. For example 'bcd', 'a', 'abcd' are substrings of the string 'abcd' whereas the strings 'bd', 'acd' are not. Function Description Complete the function countDistinctPasswords in the editor below. countDistinctPasswords has the following parameter:

  • string password: the original password Returns long integer: the number of distinct password strings that can be formed

Constraints

  • All characters in password are lowercase English letters ascii[a-z]
  • 1 ≤ length of password ≤ 10⁵
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

A team of data analysts at Amazon is working to identify patterns in data. During their analysis, they discovered a category of strings they call a 'dominant string': The string has an even length. The string contains at least one character with a frequency equal to exactly half the length of the string. Given a string s of length n, determine how many of its substrings are dominant strings. Function Description Complete the function countDominantSubstrings in the editor. countDominantSubstrings has the following parameter:

  • String s: the string to analyze Returns int: the number of dominant substrings

Example 1

Input:

s = "aaaaid"

Output:

3

Explanation: 'aa', 'id', and 'aaid' are dominant substrings.

Example 2

Input:

s = "abab"

Output:

4

Explanation: Here are the dominant substrings in s = "abab":

  • "ab" (from position 0 to 1):
  • Length 2, 'a' and 'b' both appear once, which is exactly half of the length (2 / 2 = 1).
  • "ba" (from position 1 to 2):
  • Length 2, 'b' and 'a' both appear once, which is exactly half of the length (2 / 2 = 1).
  • "ab" (from position 2 to 3):
  • Length 2, 'a' and 'b' both appear once, which is exactly half of the length (2 / 2 = 1).
  • "abab" (from position 0 to 3):
  • Length 4, 'a' appears twice, which is exactly half of the length (4 / 2 = 2). The dominant substrings are "ab", "ba", another occurrence of "ab", and "abab", making a total of 4.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Hello! This problem is identified as a duplcate of Count Inaccurate Results (This is a text button) In an Amazon computing environment, there is a critical sequence of n processes that must be executed in a specific order for accurate results. The process order is represented by the array requiredSequence, where requiredSequence[i] (1 ≤ i ≤ n) denotes the process to be executed at the i-th position. Accurate results require the execution of all preceding processes. Facing a challenge, an individual guided by the array actualSequence mistakenly runs the processes in a different order, where actualSequence[i] (1 ≤ i ≤ n) signifies the process executed at the i-th position. Both requiredSequence and actualSequence are permutations of size n. Determine the count of processes that fail to produce accurate results due to the deviation from the specified order. A permutation is a sequence of integers from 1 to n of length n containing each number exactly once, for example [3, 2, 1] is a permutation while [1, 2, 1] is not. Function Description Complete the function countFailedExecutions in the editor. countFailedExecutions has the following parameters:

  • int requiredSequence[n]: order in which the processes should be executed
  • int actualSequence[n]: order in which the processes were actually executed Returns int: the count of processes that fail to produce accurate results due to the deviation from the specified order

Constraints

  • 1 ≤ n ≤ 2*10⁵
  • 1 ≤ requiredSequence[i], actualSequence[i] ≤ n
  • requiredSequence and actualSequence are permutations of integers from 1 to n

Example 1

Input:

requiredSequence = [4, 2, 3, 5, 1, 6]
actualSequence = [2, 3, 5, 1, 6, 4]

Output:

5

Explanation: The only difference between the arrays requiredSequence and actualSequence is that process 4 is executed first after all other processes, while the order of the remaining processes remains unchanged. Additionally, processes 2, 3, 5, 1, and 6 rely on process 4 to produce accurate results. However, since process 4 is executed after these processes, none of them yield accurate results. Process 4, which does not depend on any other process for successful execution, still produces correct results. As a result, the number of processes yielding inaccurate results is 5.

Example 2

Input:

requiredSequence = [3, 2, 1]
actualSequence = [3, 2, 1]

Output:

0

Explanation: We see that the order of execution of processes in actualSequence matches that of requiredSequence. Therefore, every process gives accurate results. Hence, 0 processes give inaccurate results, and we return that.

Example 3

Input:

requiredSequence = [2, 3, 5, 1, 4]
actualSequence = [5, 2, 3, 4, 1]

Output:

2

Explanation: We see that 2 processes would give inaccurate results and these would be the process 5 and 4. Process 5 gives inaccurate results because in the original order, it needs processes 2 and 3 to run successfully, and the individual executes both of the mafter process 5. Also process 4 needs all the other processes to be executed before it runs properly. But the individual executes process 1 afterward, resulting in 4 giving inaccurate results. So, 2 processes give inaccurate results, and we return that.

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

Implement a prototype service to automate the detection and replacement of faulty servers to improve the availabity of an application. There are n servers with its s1, s2,...,s_n, and an array of strings, logs, of size m. Log format is "<server_id> <success/error>", the id of the server and the status of the processed request. If a perticular server id logs an error for three consecutive requests, it is considered faulty and is replaced with a new server with the same id. Given n and athe array logs, find the number of times a faulty server was replace. Function Description Complete the function countFaults in the editor . countFaults has the following parameter:

  • int n: the number of servers
  • String logs[m]: the application logs Returns int: the number of times servers were replaced

Constraints

  • 1 ≤ n ≤ 200
  • 1 ≤ m ≤ 2 * 10⁴ (The source image is too blurry. It looked like 10⁴ to me. If you find it incorrect, please let me know! Many thanks in advance )

Example 1

Input:

n = 2
logs = ["s1 error", "s1 error", "s2 error", "s1 error", "s1 error", "s2 success"]

Output:

1

Explanation: s1 was replaced one time. So output should be 1.

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

Given an integer k and a list of integers, count the number of distinct valid pairs of integers (a, b) in the list for which a + k = b. Two pairs of integers (a, b) and (c, d) are considered distinct if at least one element of (a, b) does not also belong to (c, d). Note that the elements in a pair might be the same element in the array. An instance of this is below where k = 0. Function Description Complete the function countPairs in the editor. countPairs has the following parameter(s):

  • int numbers[n]: array of integers
  • int k: target difference Returns int: number of valid (a, b) pairs in the numbers array that have a difference of k

Constraints

  • 2 ≤ n ≤ 2 * 10⁵
  • 0 ≤ numbers[i] ≤ 10⁹, where 0 ≤ i < n
  • 0 ≤ k ≤ 10⁹</

Example 1

Input:

numbers = [1, 1, 1, 2]
k = 1

Output:

1

Explanation: This arr has 3 different valid pairs: (1, 1), (1, 2), and (2, 2,). For k = 1, there is only 1 valid pair which satisfies a + k = b: the pair (a, b) = (1, 2)

Example 2

Input:

numbers = [1, 2]
k = 0

Output:

2

Explanation: This arr has 3 different valid pairs: (1, 1), (1, 2), and (2, 2,). For k = 0, there is only 2 valid pair which satisfies a + k = b: 1 + 0 = 1 and 2 + 0 = 2.

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

In Amazon computing environment, there is a critical sequence of n processes that must be executed in a specific order to produce results. The prescribed order is represented by the array processOrder, where processOrder[i] (1 ≤ i ≤ n) denotes the process to be executed at the ith position. Accurate results require the execution of all n preceding processes. Facing a challenge, an individual, guided by the array executionOrder, mistakenly runs the processes in a different order. Here, executionOrder[i] (1 ≤ i ≤ n) signifies the process executed at the ith position. Both processOrder and executionOrder are permutations of size n. Determine the count of processes that fail to produce accurate results due to the deviation from the specified order. A permutation is a sequence of integers from 1 to n of length n containing each number exactly once, for example [1, 3, 2] is a permutation while [1, 2, 2] is not.

Constraints

  • 1 ≤ n ≤ 2*10⁵
  • actualSequence[i] ≤ n, actualSequence[i] ≤ n
  • requiredSequence and actualSequence are permutations of integers from 1 to n

Example 1

Input:

processOrder = [2, 3, 5, 1, 4]
executionOrder = [5, 2, 3, 4, 1]

Output:

2

Explanation: We see that 2 processes would give inaccurate results and these would be the process number 5 and 4. Process 5 gives inaccurate results because in the original order, it needs processes 2 and 3 to run successfully, and the individual executes both of them after process 5. Also, process 4 needs all the other processes to be executed before it runs properly. But the individual executes process 1 afterward, resulting in 4 giving inaccurate results. Therefore, 2 processes give inaccurate results.

Example 2

Input:

processOrder = [4, 2, 3, 5, 1, 6]
executionOrder = [2, 3, 5, 1, 6, 4]

Output:

5

Explanation: The only difference between the arrays processOrder and executionOrder is that process 4 is executed after all other processes, while the order of the remaining processes remains unchanged. Additionally, processes 2, 3, 5, 1, and 6 rely on process 4 to produce accurate results.

Example 3

Input:

processOrder = [3, 2, 1]
executionOrder = [3, 2, 1]

Output:

0

Explanation: We see that the order of execution of processes in executionOrder matches that of processOrder. Hence, 0 processes give inaccurate results. Therefore, 0 processes give inaccurate results, and we return that.

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

In an Amazon security analysis task, two passwords have been generated, but they may be differ in length. One password is generated by a customer, and the other by an internal system. The customer wants to determine how many secured variations of the passwords exist module 10⁹ + 7. An secured variation of the passwords is defined as a subsequence of customer's password which is lexicographically greater than system generated password. Formally: Person A has a password s (the customer's password) Person B has a password t (the system-generated password) The task is to count how many susequences of password s are lexicographically greater than password t. Since the answer can be large, return the result module (%) 10⁹ + 7. More specifically, if result represents the required number of subsequences, then return the remainder when result is divided by 10⁹ + 7. Note A subsequence is determined as a sequence derived from the original password by deleting zero or more characters without changing the order of the remaining characters. For example, "ac" is a susequence of "abc", but "ca" is not. A sequence x is considered lexicographically greater than a sequence y if: -->x[i] > y[i] at the first position where x and y differ. or -->|x| > |y| and y is a prefix of x (where |x| denotes the length of password x). Thanks a jillion, spike!

Constraints

  • 1 ≤ |s| ≤ 10⁵
  • 1 ≤ |t| ≤ 100
  • s and t consists of lowercase English letters.

Example 1

Input:

s = "aba"
t = "ab"

Output:

3

Explanation: From all posibble subsequences, 3 are lexicographically smaller, 1 is equal, and 3 are greater than t, hence the answer is 3 :)

Example 2

Input:

s = "bab"
t = "ab"

Output:

5

Explanation: Lets examine all possible susequences that can be derived from s = "bab" and compare them lexicographically with t = "ab": The rest of the explanation is not complete, so I did not add them here :)

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

You are given a DNA sequence string genome, consisting of lowercase Latin letters. A substring of genome is considered special if it satisfies one of the following conditions: The length of the substring is exactly 2 and both characters are the same. Example: "aa", "bb" The length of the substring is greater than 2, the first and last characters are the same, and the substring in between (from index 1 to n-2) contains exactly one distinct character. Example: "xyyx" -> 'x' == 'x' and the middle "yy" has only one distinct character. Function Signature def countSpecialSubstrings(genome: str) -> int: Input • A single string genome of length n where:

  • 1 ≤ n ≤ 3 * 10⁵
  • genome contains only lowercase letters ('a' to 'z') Output • Return the total count of special substrings in the given genome string.

Constraints

• 1 ≤ |genome| ≤ 300,000

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

Imagine you're working with Amazon's data analysis team, specifically focusing on analyzing customer behavior through clickstream data. This data consists of sequences of user actions on the website, represented as binary strings. A '1' could represent a significant action (like adding an item to the cart of making a purchase), and a 'O' could represent a less significant action (like browsing or viewing a product). You are given a binary string s that represents a user's interaction history. A behavior pattern (substring) is considered "special" if the number of insignificant actions ('O's) equals the square of the number of significant actions ('1's) within that pattern. The challenge is to identify and count all "special" behavior patterns in the user's interaction history. These patterns might indicate critical points in the user's journey where their browsing behavior was well-balanced with key actions, which could be important for understanding user engagement or predicting future purchases. Function Description Complete the function countSpecialSubstrings in the editor. countSpecialSubstrings has the following parameter:

  • String s: a binary string representing user interaction history Returns int: the count of special behavior patterns

Constraints

  • 1 ≤ |s| ≤ 10⁵
  • s consists of '0' and '1' only
  • complete constraints were added on 06-13-2025

Example 1

Input:

s = "010001"

Output:

4

Explanation: s[0,1] ("01") and s[4,5] ("01") are special because they have 1 significant action ('1') and 1 insignificant action ('0'), satisfying the condition cnto = cnt, * cnt. s[0,5] ("010001") is special because it has 2 significant actions ('1') and 4 insignificant actions ('O), also satisfying the condition cnto = cnt, * cnty. s[1,2] ("10") is special as it has 1 significant action and 1 insignificant action. In total, the string "010001" contains 4 special substrings, indicating balanced periods of interaction in the user's journey.

Example 2

Input:

s = "10010"

Output:

3

Explanation: The special binary strings are s[0, 1] ("10"), s2, 3, and s3, 4. This test case was added on 06-13-2025. Relevant source image was included in the Problem Source section below.

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

Given a string s, return the numbe

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists of lowercase English letters.

Example 1

Input:

s = "abc"

Output:

3

Explanation: Three palindromic strings: "a", "b", "c".

Example 2

Input:

s = "aaa"

Output:

6

Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

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

You are given an integer representing a total count of wheels. Your task is to determine how many distinct ways you can form a group of vehicles using an unlimited supply of two-wheeled and four-wheeled types such that the sum of their wheels equals the given total. Two arrangements are considered unique if the count of two-wheeled or four-wheeled vehicles used differs between them. The function should return a list of integers, where each value corresponds to the number of valid combinations for the respective total in the input list. Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ wheels[i] ≤ 10⁹

Example 1

Input:

wheels = [6, 3, 2]

Output:

[2, 0, 1]

Explanation: For a total of 6 wheels: Option 1: One four-wheeled vehicle + one two-wheeled vehicle Option 2: Three two-wheeled vehicles Total combinations = 2

For 3 wheels: No possible arrangement can sum to 3 wheels using only 2- and 4-wheeled vehicles Total combinations = 0

For 2 wheels: Only possible using one two-wheeler Total combinations = 1

Example 2

Input:

wheels = [4, 5, 6]

Output:

[2, 0, 2]

Explanation: For 4 wheels: either 1 four-wheeler or 2 two-wheelers. For 5 wheels: it is impossible. For 6 wheels: either 1 four-wheeler + 1 two-wheeler or 3 two-wheelers.

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

Your development team has been assigned the task of designing a dynamic array generator tool to support software testing workflows. This generator service is designed to create an array that adheres to specific selection and unlocking rules. The function takes the following parameters: elements[n]: an array of n positive integers. availability: a string of n characters where:

  • Each character is either '0' or '1'.
  • If availability[i] = '1', the corresponding elements[i] is selectable.
  • If availability[i] = '0', the corresponding elements[i] is initially locked. To construct an output array, resultSet, the following process is executed exactly operations times. Initially, resultSet is empty. Choose any available element elements[i], where availability[i] = '1'. Elements can be selected multiple times. Append the chosen value to resultSet. For any availability[i] = '0' where availability[i-1] = '1', update availability[i] to '1'. For instance, if availability was '0100101' before selection, it would become '0110111' after selection. The goal is to generate the lexicographically largest possible sequence resultSet after operations selections. Note: A sequence x is considered lexicographically larger than sequence y if there exists an index i (0 ≤ i y[i], and for any j (0 ≤ j < i), x[j] = y[j].

Constraints

N/A

Example 1

Input:

elements = [10, 5, 7, 6]
availability = "0101"
operations = 2

Output:

[6, 7]

Explanation: This test case was added on March 1, 2025, for your testing convenience. Relevant information is included in the source image section below. Step 1: Initially, only {6} is available since availability[3] = '1'. Step 2: Select 6. This unlocks availability[2], making {7} available. Step 3: Select 7. We have now performed operations = 2 selections.

Example 2

Input:

elements = [4, 9, 1, 2, 10]
availability = "10010"
operations = 4

Output:

[4, 9, 10, 10]

Explanation: This test case was added on March 1, 2025, for your testing convenience. Relevant information is included in the source image section below. Step 1: Initially available elements: {4, 10}. Step 2: Select 4, unlocking availability[1] → {4} → {9}. Step 3: Select 9, unlocking availability[2] → {9} → {1}. Step 4: Select 10, unlocking availability[3] → {10} → {2}. Step 5: Select 10 again.

Example 3

Input:

arr = [5, 3, 4, 6]
state = "1100"
m = 5

Output:

[5, 5, 6, 6, 6]

Explanation: N/A If you happen to know about it, pls feel free to lmk! Manyyy thanks in acvance!

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

AWS provides several utilities for language processing. Develop a helper service to sort a list of strings based on a custom order of characters. More formally, you are given a custom alphabet system that consists of exactly k characters. Their sorted alphabetical order is given by a string of distinct characters, order. An array arr contains n strings to sort according to the special ordering. Each string in arr contains only characters in order. Note: A string x = x1x2 ... xn is lexicographically smaller than string y = y1y2 ... ym if either n Function Description Complete the function customSortStringin the editor below.customSortString` has the following parameters:

  • string order: the custom order alphabet of k characters
  • string arr[n]: the strings to sort Returns string(s): the sorted strings Endless gratitude to the best spike!

Constraints

  • 1 ≤ k ≤ 62
  • 1 ≤ n ≤ 10⁵
  • The sum of lengths of all strings in arr does not exceed 10⁶.
  • All characters of arr[] are present in order.
  • All characters of order are distinct and consist of [a-zA-Z0-9] only.

Example 1

Input:

order = "9AacB"
arr = ["BBBBa", "BBBB9", "B9ca", "Aa999", "B9A", "B", "B9A"]

Output:

["Aa999", "B", "B9A", "B9A", "B9ca", "BBB89", "BBBBa"]

Explanation: order = "9AacB" so 'A' comes before 'B', '9' comes before 'B', 'A' comes before 'c', 'c' comes before 'B', '9' comes before 'a'. The sorted order of strings is ["Aa999", "B", "B9A", "B9A", "B9ca", "BBB89", "BBBBa"].

Example 2

Input:

order = "yYaAbBl"
arr = ["Yay", "yaY", "lyab", "lyab", "b", "bay"]

Output:

["yaY", "Yay", "b", "bay", "lyab", "lyaB"]

Explanation: tomtom highly recommend to go with this highlighted explanation - For example 2, order = "yYaAbB1". The last character might supposed to be letter l, not number one. hard to say. In the explanation they use number one, but it looks like letter l in the example. Regardless, make sure it's both letter l in arr and order or both number one in arr and order.

  • by spike in Nov 2024 :) ( ^◡^)っ -ˋˏ┈┈┈┈-ˋˏ┈┈┈┈-ˋˏ┈┈┈┈-ˋˏ┈┈┈┈-ˋˏ┈┈ Original explanation from the source that is likely to be wrong - order = "yYaAbB1" so 'y' comes before 'Y', 'Y' is before 'b', 'b' is before '1', 'y' is before 'a' and 'b' is before 'B'. The sorted order of strings is ["yaY", "Yay", "b", "bay", "lyab", "lyaB"].

Example 3

Input:

order = "7BbAz"
arr = ["Abb", "A7z", "z7AAAA", "BbbABB"]

Output:

["BbbABB", "A7z", "Abb", "z7AAAA"]

Explanation: The sorted srings are ["BbbABB", "A7z", "Abb", "z7AAAA"]

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

Given two strings, searchWord and resultWord: Determine the minimum number of characters you need to append to resultWord so that it becomes a subsequence of searchWord. Example: Input: searchWord = "abcz" resultWord = "azdb" Output: 2 Explanation: By appending 'd' and 'b' to "azdb", we can transform it into a subsequence of "abcz". Understanding the Problem: A subsequence of a string is derived by deleting some or no characters from it without changing the order of the remaining characters. For example: "ace" is a subsequence of "abcde" because 'a', 'c', and 'e' appear in order. "ace" is NOT a subsequence of "abcde" because 'e' appears before 'c'. In this problem: Input: Two strings, searchWord and resultWord. Output: The number of characters to append to resultWord so that all characters in resultWord appear in order as a subsequence in searchWord.

Example 1

Input:

searchWord = "abcz"
resultWord = "azdb"

Output:

2

Explanation: By appending 'd' and 'b' to "azdb", we can transform it into a subsequence of "abcz".

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

Imagine that the Banana Company is managing a queue of tasks that need to be executed sequentially. Each task is defined by its processing time, represented in an array taskDurations[], where each index refers to a specific task. The execution of these tasks happens one after another, without any parallel processing. The execution happens in work shifts, where each shift has a specified duration, represented by workShifts[]. If a task isn't fully completed within the allocated shift time, it continues in the subsequent shift. At the beginning of each shift, the processing resumes from where it left off in the previous shift. Your objective is to determine the count of unfinished tasks at the conclusion of each shift. Function Description Complete the function computeUnfinishedTasks in the editor. computeUnfinishedTasks has the following parameters:

    1. int[] taskDurations: an array of integers denoting the processing time required for each task
    1. int[] workShifts: an array of integers representing the duration of each shift Returns int[]: an array of integers indicating the number of unfinished tasks remaining after each shift

Constraints

  • 1 ≤ n, m ≤ 2 * 10⁵
  • 1 ≤ taskDurations[i], workShifts[i] ≤ 10⁹

Example 1

Input:

taskDurations = [1, 4, 4]
workShifts = [9, 1, 4]

Output:

[0, 2, 1]

Explanation: This test case was added on 03-02-2025 for your testing convenience. You can find the source image in the Problem Source section below.

Example 2

Input:

taskDurations = [1, 2, 4, 1, 2]
workShifts = [3, 10, 1, 1, 1]

Output:

[3, 0, 4, 4, 3]

Explanation: This test case was added on 03-02-2025 for your testing convenience. You can find the source image in the Problem Source section below. Hence, the number of unfinished tasks left after each workshift is [3, 0, 4, 4, 3].

Example 3

Input:

taskDurations = [2, 4, 5, 1, 1]
workShifts = [1, 5, 1, 5, 2]

Output:

[5, 3, 3, 1, 0]

Explanation: Shift 1: The first task is only partially completed, leaving [1, 4, 5, 1, 1] still to be done. At the end of Shift 1, 5 tasks remain unfinished. Shift 2: The first two tasks are fully processed, reducing the remaining work to [0, 0, 5, 1, 1]. After Shift 2, the pending tasks are "5, 1, 1", leaving 3 tasks unfinished. Shift 3: The third task is partially completed, with the remaining work now being [0, 0, 4, 1, 1]. After Shift 3, the remaining tasks are "4, 1, 1", meaning 3 tasks are still incomplete. Shift 4: The third and fourth tasks are completely processed, leaving [0, 0, 0, 0, 1]. After Shift 4, only 1 task is still pending. Shift 5: The last task is completed, resulting in [0, 0, 0, 0, 0]. By the end of Shift 5, all tasks have been processed! Thus, the number of unfinished tasks after each shift is: [5, 3, 3, 1, 0].

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

It seems like this is a brand-new question recently asked by Amazon—I couldn’t find it in our question bank. The examples and test cases are just placeholders for now, but the problem statement should be able to give us a general idea of what they're asking. I’ll share more details once I find reliable sources. Good news updated on 06-25-2025 - Finally found the missing parts! No more placeholder. We now can start practicing! You and a colleague are responsible for dispatching goods from multiple warehouses. The inventory[i] array represents the amount of stock in each warehouse. Rules: Each warehouse is initially handled by you, and you dispatch dispatch1 units of goods from it. Then it's your colleague's turn, and he can either:

  • Dispatch dispatch2 units of goods, or
  • Skip his turn. He can skip up to skips times in total (across all warehouses). The two of you alternate turns until the warehouse is emptied, then move on to the next warehouse. A point is earned only if you are the one who removes the last unit of goods from a warehouse (i.e., the warehouse becomes empty on your turn). Goal: Determine the best skipping strategy for your colleague (i.e., in which warehouses he should skip) to maximize the total number of points you and your colleague can earn. Return the maximum number of points that can be obtained. Function Description Complete the function maxPoints in the editor. maxPoints has the following parameters:
    1. int[] inventory: an array representing the stock in each warehouse
    1. int dispatch1: the number of units you dispatch in your turn
    1. int dispatch2: the number of units your colleague dispatches in his turn
    1. int skips: the total number of skips your colleague is allowed Returns int: the maximum number of points that can be obtained

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ inventory[i]

Example 1

Input:

inventory = [10, 6, 12, 8, 15, 1]
dispatch1 = 2
dispatch2 = 3
skips = 3

Output:

5

Explanation: An optimal dispatch strategy would be ~

  1. Your co-worker skips 2 turns, allowing you to empty the inventory of the 1st warehouse (Inventory: 10 -> 8 -> 5 -> 3 -> 1 -> -1).
  2. Your co-worker does not skip any turns, and you empty the inventory of the 2nd warehouse (Inventory: 6 -> 4 -> 1 -> -1).
  3. Your co-worker does not skip any turns, and you empty the inventory of the 3rd warehouse (Inventory: 12 - > 10 -> 7 -> 5 -> 2 -> 0).
  4. Your co-worker skips 1 turn, and you drain the inventory of the 4th warehouse (Inventory: 8 -> 6 -> 3 -> 1 -> -1).
  5. Your co-worker does not skip any turns, and they empty the inventory of the 5th warehouse (Inventory: 15 -> 13 -> 10 -> 8 -> 5 -> 3 -> 0).
  6. Your co-worker does not skip any turns, and you empty the inventory of the 6th warehouse (Inventory: 1 -> -1). As a result, the 1st, 2nd, 3rd, 4th, and 6th warehouses were completely dispatched by you, and the two of you collectively earned 5 credits! This is the maximum possible in this scenario. So, answer is 5. This test case example was added on 06-25-2025. Relevant source image was added in the Problem Source section below.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

A general store at Hackerland sells n items with the price of the i^th item represented by price[i]. The store adjusts the price of the items based on inflation as queries of two types: 1 x v: Change the price of the x^th item to v. 2 v v: Change any price that is less than v to v. Given an array price of n integers and the price adjustment queries are in the form of a 2-d array where query[i] consists of 3 integers, find the final prices of all the items. Function Description Complete the function finalPrices in the editor. finalPrices has the following parameters:

  • n: an integer, the number of items
  • int price[n]: an array of integers representing the prices
  • q: an integer, the number of queries
  • int queries[q][3]: a 2D array of price adjustment queries Returns int[]: an array of integers representing the final prices
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

The general meaning of the question is as described. I will follow up in detail once I find reliable sources. The second question is about distributing games to N children. There are m games in total, and the memory size of each game is stored in an array. You need to prepare N hard drives to distribute the games to the children. The requirement is that each child must receive at least one game, and all games must be distributed. The question asks: What is the minimum memory capacity required for each of the N hard drives?

Example 1

Input:

games = [6, 7, 10, 12, 1]
N = 3

Output:

13

Explanation: The minimum memory for each hard drive would be 13.

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

Amazon has to distribute multiple packages across all of their delivery trucks. Given an array of trucks where trucks[i] represents the ith truck quantity. We also have another input to_distribute which states the number of packages we want to distribute across all the trucks. So how would we distribute the to_distribute number such that the max total of each truck is minimized? Function Description Complete the function distributePackages in the editor. distributePackages has the following parameters:

    1. int[] trucks: an array of integers representing the quantity of each truck
    1. int to_distribute: the number of packages to distribute Returns int[]: an array representing the distributed packages across the trucks
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Amazon is expanding a next-generation drone delivery network. The network has m hubs arranged in a circular ring. Hub 1 is adjacent to hub m, and every hub is adjacent to its previous and next hub on the ring. The array transitionTime has length m. Moving directly between hub i and hub i + 1 takes transitionTime[i - 1] time. Moving directly between hub m and hub 1 takes transitionTime[m - 1] time. Amazon receives a list of priority delivery requests. The drone must visit the hubs in the order given by requestedHubs. The drone starts at hub 1. For each requested hub, the drone may move clockwise or counter-clockwise around the ring. Return the minimum total travel time needed to visit all requested hubs in order. Use 1-based hub indexing for requestedHubs.

Constraints

  • 1 ≤ transitionTime.length ≤ 10⁵
  • 1 ≤ requestedHubs.length ≤ 10⁵
  • 1 ≤ transitionTime[i] ≤ 10⁹
  • 1 ≤ requestedHubs[i] ≤ transitionTime.length

Example 1

Input:

transitionTime = [3,2,1]
requestedHubs = [1,3,3,2]

Output:

3

Explanation: The drone starts at hub 1. Visiting hub 1 costs 0. Moving from hub 1 to hub 3 is shortest through the direct edge between hubs 3 and 1, costing 1. Moving from hub 3 to hub 3 costs 0. Moving from hub 3 to hub 2 costs 2. The total is 3.

Example 2

Input:

transitionTime = [5,1,2,6]
requestedHubs = [2,4,1]

Output:

14

Explanation: From 1 to 2 costs 5. From 2 to 4, the shortest path is 2 -> 3 -> 4 with cost 1 + 2 = 3. From 4 to 1, the direct edge costs 6. The total is 5 + 3 + 6 = 14.

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

On Amazon Prime Day, non-critical requests for a transaction system are routed through a throttling gateway to ensure that the network is not choked by non-essential requests. The gateway has the following limits: The number of transactions in any given second cannot exceed 3. The number of transactions in any given 10 second period cannot exceed 20. A ten-second period includes all requests arriving from time T to T-9 (inclusive of both) for any valid time T. The number of transactions in any given minute cannot exceed 60. Similar to above, 1 minute is from max(T, T-59) to T. Any request that exceeds any of the above limits will be dropped by the gateway. Given the times at which different requests arrive sorted ascending, find how many requests will be dropped. Note: Even if a request is dropped it is still considered for future calculations. Although, if a request is to be dropped due to multiple violations, it is still counted only once. Function Description Complete the function droppedRequests in the editor. droppedRequests has the following parameter(s):

  • List requestTime: an ordered list of integers that represent the times of various requests Returns int: the total number of dropped requests

Constraints

  • 1 ≤ n ≤ 10⁶
  • 1 ≤ requestTime[i] ≤ 10⁹

Example 1

Input:

requestTime = [1, 1, 1, 1, 2]

Output:

1

Explanation:

  1. Request 1 - Not Dropped.
  2. Request 1 - Not Dropped.
  3. Request 1 - Not Dropped.
  4. Request 1 - Dropped. At most 3 requests are allowed in one second.
  5. Request 2 - Not Dropped.

Example 2

Input:

requestTime = [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7]

Output:

2

Explanation:

  1. Request 1 - Not Dropped.
  2. Request 1 - Not Dropped.
  3. Request 1 - Not Dropped.
  4. Request 1 - Dropped. At most 3 requsts are allowed in one second.
  5. Request 2 - Not Dropped.
  6. Request 2 - Not Dropped.
  7. Request 2 - Not Dropped.
  8. Request 3 - Not Dropped.
  9. Request 3 - Not Dropped.
  10. Request 3 - Not Dropped.
  11. Request 4 - Not Dropped.
  12. Request 4 - Not Dropped.
  13. Request 4 - Not Dropped.
  14. Request 5 - Not Dropped.
  15. Request 5 - Not Dropped.
  16. Request 5 - Not Dropped.
  17. Request 6 - Not Dropped.
  18. Request 6 - Not Dropped.
  19. Request 6 - Not Dropped.
  20. Request 7 - Not Dropped. The total count of requests in the 10-second period from the first to the seventh second is 21, which exceeds the limit (21 > 20), so 1 request is dropped.
  21. Request 7 - Dropped.

Example 3

Input:

requestTime = [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 11, 11, 11, 11]

Output:

7

Explanation:

  1. Request 1 - Not Dropped.
  2. Request 1 - Not Dropped.
  3. Request 1 - Not Dropped.
  4. Request 1 - Dropped. At most 3 requsts are allowed in one second.
  5. No request will be dropped till 6 as all comes at an allowed rate of 3 requests per second and the 10-second clause is also not violated.
  6. Request 7 - Not Dropped. The total number of requests has reached 20 now.
  7. Request 7 - Dropped. At most 20 requests are allowed in ten seconds.
  8. Request 7 - Dropped. At most 20 requests are allowed in ten seconds.
  9. Request 7 - Dropped. At most 20 requests are allowed in ten seconds. Note that the 1-second limit is also violated here.
  10. Request 11 - Not Dropped. The 10-second window has now become 2 to 11. Hence the total number of requests in this window is 20 now.
  11. Request 11 - Dropped. At most 20 requests are allowed in ten seconds.
  12. Request 11 - Dropped. At most 20 requests are allowed in ten seconds.
  13. Request 11 - Dropped. At most 20 requests are allowed in ten seconds. Also, at most 3 requests are allowed per second.
  14. Hence, a total of 7 requests are dropped.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Amazon SQS is a completely operated platform in the AWS ecosystem that enables dispatchers to submit and receivers to collect messages. Each message present in the sequence is symbolized by an integer, where a positive number indicates a submission by a dispatcher and a negative number denotes a retrieval by a receiver. The behavior of the queue is controlled by the "processing burden," calculated as the cumulative sum of message values over any consecutive group of messages. To guarantee the queue's consistent operation, it is essential that the processing burden for any contiguous block of messages is never zero. A processing burden of zero would signify that the queue has lost its functional purpose, which is an undesirable sadness... :( As a sharp software engineer with a total compensation of 1.5M USD, your objective is to compute the least number of additional messages that must be injected into the sequence. Each added message may carry any integer value. The intention is to ensure that once these are inserted, no segment within the sequence yields a total processing burden of zero. Given the array queueMessages, determine the minimal count of insertions necessary to fulfill this requirement.

Example 1

Input:

queueMessages = [1, -5, 3, 2, -5]

Output:

1

Explanation: The SQS Queue contains a continuous segment [2, 4] that results in a processing burden of 0. One potential approach to adjust the provided array queueMessages is by placing a message carrying the value 100 after the third position. The revised array turns into [1, -5, 3, 100, 2, -5]. At this point, no consecutive segment within the array sums up to zero. Therefore, the least number of messages required to be inserted is 1.

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

At one of Amazon’s busy warehouses, Team Alpha and Team Beta are assigned the task of processing n products for shipment. Each product handled by Team Alpha is labeled as inventory_alpha[i], and the corresponding product handled by Team Beta is labeled as inventory_beta[i]. For every product pair (inventory_alpha[i], inventory_beta[i]), Team Alpha is allowed to repeatedly perform the following operation on their product label: Pick any two distinct lowercase alphabet letters char1 and char2. Swap every occurrence of char1 with char2 throughout the entire string (and vice versa). The chosen characters don’t both have to exist in the string — it’s valid if either char1 or char2 is missing. Your task is to determine, for each product pair, whether Team Alpha can transform inventory_alpha[i] into inventory_beta[i] by performing the swap operation any number of times (including zero), while following these constraints: For each index i where 1 ≤ i ≤ n, Team Alpha may repeatedly: Select any two distinct lowercase letters ch1 and ch2. Swap every occurrence of ch1 with ch2, and every occurrence of ch2 with ch1 within the string. The original problem asks to return bool[], but I modified it to int[]. 1 represents true, while 0 represents false.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ |inventory_alpha[i]|, |inventory_beta[i]| ≤ 2*10⁵
  • |inventory_alpha[i]| = |inventory_beta[i]|
  • inventory_alpha[i] and inventory_beta[i] contain only lowercase Latin letters.
  • The sum of lengths of all strings in inventory_alpha and inventory_beta does not exceed 5 * 10⁵

Example 1

Input:

inventory_alpha = ["abba"]
inventory_beta = ["adda"]

Output:

1

Explanation: It is possible to transform "abba" to "adda" by replacing b with d. Hence our answer is 1!

Example 2

Input:

inventory_alpha = ["azzel"]
inventory_beta = ["apple"]

Output:

1

Explanation: Swap every occurrence of 'z' with 'p', transforming "azzel" into "appel". Then replace 'l' with 'e' and 'e' with 'l'. After performing these swaps, inventory_alpha = "azzel" becomes identical to inventory_beta = "apple".

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

Amazon Web Services (AWS) has several processors for executing processes scheduled on its servers. There are n processes to be executed, where the i^th process takes execution[i] amount of time to execute. Two processes are cohesive if and only if their original execution times are equal. When a process with execution time execution[i] is executed, it takes execution[i] time to complete and simultaneously reduces the execution time of all its cohesive processes to ceil(execution[i] / 2). Given the execution time of n processes, find the total amount of time the processor takes to execute all the processes if you execute the processes in the given order, i.e. from left to right. Notes The ceil() function returns the smallest integer that is bigger or equal to its argument. For example, ceil(1.1) = 2, ceil(2.5) = 3, ceil(5) = 5, etc. If the execution time of some process i is reduced and becomes equal to the execution time of any other process j, then the two processes i and j are not considered cohesive. Function Description Complete the function totalExecutionTime in the editor. totalExecutionTime has the following parameter: int execution[n]: an array of integers representing the execution times Returns int: the total amount of time to execute all processes

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ execution[i] ≤ 10⁹

Example 1

Input:

execution = [5, 5, 3, 6, 5, 3]

Output:

21

Explanation: processes 1, 2, 5 are cohesive processes 3, 6 are cohesive process 4 is cohesive Excuting Process 1 results in [0, 3, 3, 6, 3, 3] // total_execution = 5 Excuting Process 2 results in [0, 0, 3, 6, 2, 3] // total_execution = 8 Excuting Process 3 results in [0, 0, 0, 6, 2, 2] // total_execution = 11 Excuting Process 4 results in [0, 0, 0, 0, 2, 2] // total_execution = 17 Excuting Process 5 results in [0, 0, 0, 0, 0, 2] // total_execution = 19 Excuting Process 6 results in [0, 0, 0, 0, 0, 0] // total_execution = 21 Hence, total excution time is 21.

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

Amazon games have recently launched a new multi-player tournament on the platform. Each game of the tournament has 3 rounds. The players are provided with exactly three power boosters at the start of the game and each player is aware of the power boosters of their opponent. In each round, the player can choose to compete with any of the power boosters and any power booster can be used at most once in a particular game. In any particular round, the player with a higher power booster wins. A player X is considered to be capable of defeating player Y if there exists a rearrangement of power boosters of X such that some rearrangement of power boosters of Y can be defeated in at least 2 out of the three rounds. For example, if power boosters of X = [9, 5, 11] and Y = [7, 12, 3], then If Y uses the boosters in order [3, 7, 12] then X can use it in order [11, 9, 5] and X wins 2 out of the three games as 11 > 3 and 9 > 7. Thus X is capable of defeating Y. If X uses the boosters in order [5, 9, 11] then Y can use it in order [7, 12, 3] and Y wins 2 out of the three games as 7 > 5 and 12 > 9. Thus Y is also capable of defeating X. Another example is if X = [1, 2, 3] and Y = [3, 4, 5]. Here X is not capable of defeating Y as any rearrangement of Y can not be defeated by X in at least two rounds. Given the power boosters provided to n players where the three power boosters of the ith player are defined by (power_a[i], power_b[i], power_c[i]), find the number of players who are capable of defeating all other players in a game by using their power boosters optimally. It is guaranteed that all powers of each player's power boosters are distinct. Function Description Complete the function findCapableWinners in the editor. findCapableWinners has the following parameter:

  • int power_a[n]: the first set of power boosters
  • int power_b[n]: the second set of power boosters
  • int power_c[n]: the third set of power boosters Returns int: the number of players capable of defeating all other players ‧˚ 𖥧‧ ༉˚A big round of thanks for chizzy_elect and spike. You both are truly exceptional𓂃 ଓ․ 𓈒

Constraints

  • 2 ≤ n ≤ 10⁵
  • 1 ≤ power_a[i], power_b[i], power_c[i] ≤ 10⁹, where 0 ≤ i
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given two strings s1 and s2, find till how many days is s2 a subsequence of s1 if on every day we delete all the strings in s1 from start to end inclusive. Function Description Complete the function findDaysS2SubsequenceOfS1 in the editor. findDaysS2SubsequenceOfS1 has the following parameters:

    1. String s1: the original string
    1. String s2: the subsequence to find
    1. int[] start: the start indices
    1. int[] end: the end indices Returns int: the number of days s2 is a subsequence of s1

Example 1

Input:

s1 = "abcdefghabc"
s2 = "abc"
start = [0, 0, 1, 2, 9]
end = [1, 2, 3, 3, 10]

Output:

4

Explanation: An educated guess ~~ On day 1, deleting from index 0 to 1, the string becomes "cdefghabc" and "abc" is still a subsequence. On day 2, deleting from index 0 to 2, the string becomes "defghabc" and "abc" is still a subsequence. On day 3, deleting from index 1 to 3, the string becomes "dghabc" and "abc" is still a subsequence. On day 4, deleting from index 2 to 3, the string becomes "dhabc" and "abc" is still a subsequence. On day 5, deleting from index 9 to 10, the string becomes "dh" and "abc" is no longer a subsequence. Therefore, the answer is 4 days.

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

In an Amazon content analysis project, there is a dataset of strings, each representing distinct attributes. The goal is to determine the dominance of the most influential attribute prefix for various lengths. The dominance of a prefix, denoted as t, is measured by the number of instances in the dataset where t serves as a prefix. For example, in the dataset ["abab","ababc","abab"], the dominance of the prefix "ab" is 3, and the dominance of the prefix "aba" is 3. The most influential prefix of a specific length len is identified as the prefix with the highest dominance among all strings of the same length. If there are multiple prefixes of the same length with equivalent dominance, any prefix from that set may be considered the most influential. Formally, given the dataset s consisting of n strings, each of length m, the objective is to determine, for each prefix of length len ranging from 1 to m, the dominance of the most influential prefix of that length. Function Description Complete the function findDominance in the editor below. findDominance has the following parameters:

  • string s[]: The array of strings Returns int[]: the dominance of the most influential prefix of lengths from 1 to m Constraints
  • 2 ≤ n ≤ 500
  • 1 ≤ m ≤ 2000

Constraints

  • 2 ≤ n ≤ 500
  • 1 ≤ m ≤ 2000

Example 1

Input:

s = ["aba", "abb", "aba"]

Output:

[3, 3, 2]

Explanation: The most influential prefix of length 1 is "a" with a dominance of 3, the most influential prefix of length 2 is "ab" with a dominance of 3, and the most influential prefix of length 3 is "aba" with a dominance of 2, so the answer is [3, 3, 2] :)

Example 2

Input:

s = ["abc", "aaa", "aba"]

Output:

[3, 2, 1]

Explanation: :)

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

To guarantee the highest level of security, the developers at Amazon implement multiple layers of encryption techniques to safeguard user data and ensure it remains fully protected from any potential threats. One of the encryption methods used is a unique scheme known as the "Pascal Triangle" encryption. In this approach, numbers are transformed through a systematic reduction process that follows a specific pattern. When an array of digits is input into this system, it sums adjacent digits in a pairwise manner. After computing each sum, it extracts the rightmost digit (i.e., the least significant digit) from each result to form the next sequence. As this process continues, the number of digits in each step gradually decreases by 1. This iterative procedure is repeated until only two digits remain. The final pair of digits obtained at the end of the process represents the encrypted number. Given an initial sequence consisting of the digits of a number, apply the Pascal Triangle encryption method to determine the final encrypted number. The process involves systematically reducing the sequence by summing adjacent digits and retaining only the rightmost digit of each sum at every step. Your task is to compute and return the resulting encrypted number as a string of digits, representing the final two-digit sequence derived from the encryption process.

Constraints

  • 2 ≤digit_numbers.length ≤ 5 * 10³
  • 0 ≤ digit_numbers[i] ≤ 9
  • constraints were added on 2025-03-20

Example 1

Input:

digit_numbers = [4, 5, 6, 7]

Output:

"04"

Explanation: the source said that ans for this example input was "04" :)

Example 2

Input:

digit_numbers = [1, 2, 3, 4]

Output:

"82"

Explanation: source said that ans for this example input was "82" :) This example was added on 2025-03-20 :)

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

The developers at Amazon employ several algorithms for encrypting passwords. In one algorithm, the developers aim to encrypt palindromic passwords. Palindromic passwords are ones that read the same forward and backward. The algorithm rearranges the characters to have the following characteristics: It is a rearrangement of the original palindromic password. It is also a palindrome. Among all such palindromic rearrangements, it is the lexicographically smallest. Given the original palindromic password that consists of lowercase English characters only, find the lexicographically smallest palindrome. A string s is considered to be lexicographically smaller than the string t of the same length if the first character in s that differs from that in t is smaller. For example, "abcd" is lexicographically smaller than "abdc" but larger than "abad" Note that the encrypted password might be the same as the original password if it is already lexicographically smallest. Function Description Complete the function findEncryptedPassword in the editor. findEncryptedPassword has the following parameter:

  • string password: the original palindromic password Returns string: the encrypted password

Constraints

  • 1 ≤ |password| ≤ 10⁵
  • password consists of lowercase English letters only.
  • password is a palindrome.

Example 1

Input:

password = "babab"

Output:

"abbba"

Explanation: It can be rearranged to form abbba, which is both a rearrangement of the original password and the lexicographically smallest palindrome. abbba satisfies all the requirements so we can boldly abbba.

Example 2

Input:

password = "yxxy"

Output:

"xyyx"

Explanation: Rearrange the original password to form "xyyx", which is also a palindrome and is the smallest possible rearrangement.

Example 3

Input:

password = "ded"

Output:

"ded"

Explanation: Explanation not found..

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

You are given an array of integers representing inventory stock. Your task is to find the first index where the prefix sum of the array becomes non-positive (i.e., less than or equal to 0). The prefix sum is the cumulative sum of elements from the start of the array to the current element. If no such index exists, return -1.

Constraints

  • The array contains at least one element, and its length is between 1 and (10⁵).
  • The integers in the array can range from (-10⁹) to (10⁹).

Example 1

Input:

inventory = [1, 2]

Output:

-1

Explanation: Prefix sums are [1, 3], no non-positive sum.

Example 2

Input:

inventory = [2, -4, 1]

Output:

2

Explanation: Prefix sums are [2, -2, -1], becomes non-positive at index 2.

Example 3

Input:

inventory = [1, 2, 3, -6]

Output:

3

Explanation: Prefix sums are [1, 3, 6, 0], becomes non-positive at index 3.

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

Amazon Web Services is experimenting with optimizing search queries based on the location of the first unique character in a search. You have been asked to help test the query your team has created to ensure it works as designed. A unique character is one which 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 findFirstUnique in the editor below. findFirstUnique has the following parameter(s):

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

Constraints

  • 1 ≤ len 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.

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

Banana, Amazon’s super intelligent virtual assistant, simplifies tasks such as configuring your Banana-supported gadgets, playing podcast, delivering weather forecasts, and more. The development team is crafting a new feature that recommends the best days for fishing based on weather predictions. Based on recent research, a day qualifies as suitable for fishing if the rainfall levels have been non-increasing over the past "window" days leading up to that specific day and are non-decreasing during the following "window" days after it. You are given the projected rainfall amounts for the next n days in a list called forecast. Your task is to identify all days that meet this criterion. Formally, a day is ideal if the following condition holds true: forecast[i - window] ≥ forecast[i - window + 1] ≥ ... ≥ forecast[i - 1] ≥ forecast[i] ≤ forecast[i + 1] ≤ ... ≤ forecast[i + window] Parameters: forecast[n]: A list of integers representing the predicted rainfall amount for each upcoming day. window: Just an integer..

Constraints

1 ≤ windown ≤ 2 * 10⁵ 0 ≤ forcast[i] ≤ 10⁹

Example 1

Input:

forecast = [3, 2, 2, 2, 3, 4]
window = 2

Output:

[3, 4]

Explanation: For a day to qualify as perfect, the rainfall must show a non-increasing pattern over the previous 2 days and a non-decreasing pattern over the following 2 days. Based on the scenario (visual not shown): The rainfall sequence around day 3 follows: day1 ≥ day2 ≥ day3 ≤ day4 ≤ day5, making day 3 an ideal pick. Similarly, the rainfall pattern around day 4 is: day2 ≥ day3 ≥ day4 ≤ day5 ≤ day6, marking day 4 as a valid choice. Hence, the suitable fishing days identified are [3, 4].

Example 2

Input:

forecast = [1, 0, 1, 0, 1]
window = 1

Output:

[2, 4]

Explanation: Those days are perfect fishing days~~ ~ d1 ≥ d2 ~ d3 ≥ d4 What should we return this time? [2, 4].. Enjoy your fishing days! This example was added on 2025-03-20. Source image was attached in the problem source section below..

Example 3

Input:

forecast = [1, 0, 0, 0, 1]
window = 2

Output:

[3]

Explanation: Surprise! We have a perfect fishing day ~~>> d3! d1 ≥ d2 ≥ d3 = d2 ≥ d3 ≥ d4 ~ d2 ≥ d3 ≥ d4 ≥ d5 ~ d3 ≥ d4 ≥ d5 ≥ d6 ~ d4 ≥ d5 ≥ d6 ≥ d7 p.s. I've doubled checked the explanation for you! My eye might have missed something, if you find any mistake, please let me know! I am on the Discord server~ This example was added on 2025-03-20. Source image was attached in the problem source section below..

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

The Amazon Alexa development team needs to analyze request logs across numSkills different Alexa skills to understand their performance and user engagement. The skills are indexed from 1 to numSkills, and the logs are provided as a 2D array requestLog of size m where requestLog[i] = [skill_ID, timeStamp] represents a request made at timeStamp to the skill with ID skill_ID. You are given an integer numSkills, a 2D integer array requestLogs, an integer timeWindow (representing a lookback period), and an array of queryTimes containing q queries. For each queryTime[i] determine the number of skills that did not receive a request in the time interval [queryTime[i] - timeWindow, queryTime[i]]. Return an array of length q containing the result of each of the query. Note: If for some query in the numSkills received requestLog the given time interval for that query, then answer is 0. Function Description Complete the function findIdleSkillsQuery in the editor. findIdleSkillsQuery has the following parameters:

  1. int numSkills: an integer denoting the number of skills
  2. int[][] requestLogs: 2D array denoting the request logs
  3. int[] queryTime: an integer array denoting the query times
  4. int timeWindow: an integer denoting the lookback period for queries Returns int[]: an integer array denoting the answers to the queries

Constraints

  • 1 ≤ numSkills ≤ 10⁵
  • 1 ≤ m ≤ 10⁵
  • 1 ≤ q ≤ 10⁵
  • 1 ≤ requestLogs[i][0] ≤ n
  • 1 ≤ requestLogs[i][1] ≤ 10⁵
  • 1 ≤ queryTime[i] ≤ 10⁵
  • 1 ≤ timeWindow ≤ 10⁵

Example 1

Input:

numSkills = 3
requestLogs = [[1, 3], [2, 6], [1, 5]]
queryTime = [10, 11]
timeWindow = 5

Output:

[1, 2]

Explanation: For queryTime[0] = 10, skills 1 and 2 had requests at timeStamps 5 and 6, respectively, which fall in the interval [5, 10]. Skill 3 did not receive any requests in the given interval. Thus, answer for this queryTime is 1. For queryTime[1] = 11, skill 2 requests at timeStamp6, respectively, which fall in the interval [6, 11]. Skill 1 and 3 did not receive any requests in the given interval. Thus, answer for this queryTime is 2. So, our answer turns out to be [1, 2].

Example 2

Input:

numSkills = 6
requestLogs = [[3, 2], [4, 3], [2, 6], [6, 3]]
queryTime = [3, 2, 6]
timeWindow = 2

Output:

[3, 5, 5]

Explanation: For queryTimes[0] = 3, in time interval [1, 3] skills [3, 4, 6] receives requests. For queryTime [1] = 2, in time interval [0, 2] skills [3] receives requests. For queryTime [2] = 6, in time interval [4, 6] skills [2] receives requests.

Example 3

Input:

numSkills = 6
requestLogs = [[3, 2], [4, 3], [2, 6], [6, 3]]
queryTime = [1, 2, 3, 4, 5, 6]
timeWindow = 1

Output:

[6, 5, 3, 4, 6, 5]

Explanation: o

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

You have an array from 1 to N</co

Constraints

no constraint were given

Example 1

Input:

N = 7
K = 4

Output:

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

Explanation: N/A for now

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

Note - Another problem related to find server vulnerability Find Least Possible Vulnerability Amazon Web Services has n servers where the i^th server's vulnerability score is vulnerability[i]. A client wants to deploy their application on a group of m contiguous servers. The vulnerability of a group is defined as the k^th minimum vulnerability among the chosen servers. Find the vulnerability of each possible group of m contiguous servers the client can choose. Function Description Complete the function findKthMinimumVulnerability in the editor below. findKthMinimumVulnerability has the following parameter(s):

  • int k: the order of the vulnerability to find
  • int m: the number of servers in a group
  • int vulnerability[n]: the vulnerabilities of each server Returns int[]: the vulnerabilities for each group, in order

Constraints

  • 1 ≤ k ≤ m ≤ n ≤ 3*10⁵
  • 1 ≤ vulnerability[i] ≤ 10⁹

Example 1

Input:

k = 2
m = 3
vulnerability = [1, 3, 2, 1]

Output:

[2, 2]

Explanation: There are 2 contiguous groups of m = 3 servers: [1, 3, 2] and [3, 2, 1]. The k = 2^ndnd lowest vulnerability in each group is 2. Return the answers for each group, in order: [2, 2].

Example 2

Input:

k = 3
m = 4
vulnerability = [4, 2, 3, 1, 1]

Output:

[3, 2]

Explanation: No explanation's found so far. If you happen to know about it. You're more than welcome to lmk! Many thanks in advance!

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

You are shopping online for some bags of onion. Each listing displays the number of onions that the bag contains. You want to buy a perfect set of onion bags from the entire search results list, onionBags. A perfect set of onion bags, perfect, is defined as: The set contains at least two bags of onion. When the onion bags in the set perfect are sorted in increasing order by count, it satisfies the condition perfect[i] = perfect[i+1] for all 1 ≤ i < n. Here n is the size of the set and perfect[i] is the number of onion in bag i. Find the largest possible set perfect and return an integer, the size of that set. If no such set is possible, then return -1. It is guaranteed that all elements in onionBags are distinct.

Constraints

  • 1 ≤ onionBags.length ≤ 10⁵
  • 1 ≤ onionBags[i] ≤ 10⁹

Example 1

Input:

onionBags = [3, 9, 4, 2, 16]

Output:

3

Explanation: The following are the perfect sets:

  • Set perfect = [3, 91]. The size of this set is 2.
  • Set perfect = [4, 2]. The size of this set is 2.
  • Set perfect = [4, 16]. The size of this set is 2.
  • Set perfect = [4, 2, 16]. The size of this set is 3. The size of the largest set is 3. The image below illustrates the correct ordering of the purchased onion bags by count.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Note - Another problem related to find server vulnerability Find Kth Minimum Vulnerability A great solution insight from a pro in the server. Hope it helps you solve this problem! Another pro in the server mentioned that this problem is similar to LC 1004. Hopefully, the similarity can help bring some insights for you. Happi Coding! You are not alone! Developers at Amazon IAM are working on identifying vulnerabilities in their key generation process. The key is represented as an array of n integers, where the i-th integer is denoted by key[i] The vulnerability factor of the array is defined as the maximum length of a contiguous subarray that has a Greatest Common Divisor (GCD) greater than 1. You are allowed to make at most maxChange modifications to the array, where each modification consists of changing any one element in the array to any other integer. Your task is to determine the least possible vulnerability factor of the key after performing at most maxChange modifications. If no valid subarray has GCD > 1, the vulnerability factor is considered 0. Function Description Complete the function findLeastPossibleVulnerabilityFactor in the editor. findLeastPossibleVulnerability has the following parameters:

    1. int[] key: an array of integers
    1. int maxChange: the maximum number of changes allowed Returns int: the least possible vulnerability factor of the array after performing at most maxChange modifications. A heartfelt thank you to all the amazing friends who so generously offered their help in completing this question!

Constraints

  • 1 ≤ n ≤ 10⁵
  • 0 ≤ maxChange ≤ n
  • 1 ≤ key[i] ≤ 10⁹

Example 1

Input:

key = [2, 2, 4, 9, 6]
maxChange = 1

Output:

2

Explanation: The inital vulnerability factor is 3 (subarray [2, 2, 4]). Possible modifications - Change key[0] to 3 --> [3, 2, 4, 9, 6] ---> max subarray length with GCD ----> 1 is 2 ([2, 4] and [9, 6]) Change key[2] to 5 --> [2, 2, 5, 9, 6] ---> max subarray length with GCD ----> 1 is 2 ([2, 2] and [9, 6]) The least vulnerability factor after at most 1 change is 2.

Example 2

Input:

key = [5, 10, 20, 10, 15, 5]
maxChange = 2

Output:

2

Explanation: A super huge thank you to the friend who helped verify the accuracy of this test case! :3 First Change - ~ Modify the third element of the array to 2 and the fourth element to 3, so the updated key becomes [5, 10, 2, 3, 15, 5] ~ In this case , the maximum length of a subarray with a GCD greater than 1 is 2. This applies to several subarrays: [5, 10], [10, 2], [3, 15], [15, 5] Second Change - ~ Modify the first element of the array to 7 and the fourth element to 9, so the updated key becomes [7, 10, 20, 9, 15, 5] ~ Here as well, the maximum length of a subarray with a GCD greater than 1 is 2, for the following subarrays: [10, 20], [15, 5] Thus, after making the changes, the least possible vulnerability factor of the key is 2. This official exlplanation was added on 06-17-2025 :) Relevant source image was included in Problem Source.

Example 3

Input:

key = [4, 2, 4]
maxChange = 1

Output:

1

Explanation: Currently, the array has a GCD of 2 and a length of 3, but the optimal length is 1. The only way to achieve the optimal length is to change the second element to a value a has a GCD of 1 with 4. For example, chyange the key to [4, 3, 4]. In this case, the subarray with a GCD greater tha n1 are: [4], [3], [4]. Since the maximum length of these subarrays is 1, the least possible vulnerability factor of the key is 1. This official explanation was added on 06-17-2025 :3 Relevant source image was included in Problem Source.

Example 4

Input:

key = [3, 5, 7, 11, 13]
maxChange = 2

Output:

0

Explanation: All numbers are prime, so no subarray has GCD > 1. If we change key[0] to 2 and key[1] to 4, we still can't form a valid subarray with GCD > 1. Thus, the minimum possible vulnerability factor is 0. This new test case was added on 03-28-2025.

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

The task is to determine the length of the longest isolated proper substring within a given string. An isolated proper substring must satisfy the following conditions: The substring is not the entire given string inputString. No character within the substring appears anywhere outside the substring. Given a string inputString of length n, determine the length of its longest isolated proper substring. If no such substring exists, return 0. Function Description Implement the function findLongestIsolatedSubstringLength in the editor. The function takes the following parameter:

  • String inputString: the string to analyze Returns int: the length of the longest isolated proper substring

Constraints

  • s consists of lowercase letters.
  • 1 ≤ n ≤ 10⁵

Example 1

Input:

s = "abcba"

Output:

0

Explanation: A new test case added on 03-01-2025 for your testing convenience :) The source said the expected output should be 3 - "abcba output should be : 3 (the substring will be bcb). but expected output is 0."

Example 2

Input:

s = "amazonservices"

Output:

11

Explanation: (Image updated on 2025-02-02) The longest self-sufficient proper substring is "zonservices" which has a length of 11.

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

Given a character string, find the lexicographically smallest string of the same length that is greater than the original string, with the condition that no two adjacent characters are the same. If no such string exists, return -1. The string only contains letters, with 'a' being the smallest and 'z' being the largest. Function Description Complete the function findLexicographicallySmallestString in the editor. findLexicographicallySmallestString has the following parameter:

  • String s: the original string Returns String: the lexicographically smallest string that meets the condition or "-1" if no such string exists

Example 1

Input:

s = "abbcd"

Output:

"abcab"

Explanation:

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

At Amazon, a user owns a unique tool called the "Parentheses Perfection Kit." This kit contains different types of parentheses, each with a specific efficiency rating. The goal is to create a balanced sequence of parentheses by adding zero or more parentheses from the kit to maximize the sequences total EfficiencyScore. The EfficiencyScore of a sequence is the sum of the efficiency ratings of the parentheses used from the kit. A sequence is considered balanced if it has an equal number of opening '(' and closing ')' parentheses, with each opening parentheses properly matched with a closing one in the correct order (i.e., circular balance). For instance, sequences like (()),(), and (()()) are balanced, while sequences like ), ((), and (()())) are not. You are given an initial parentheses sequence represented by the string s, along with a Parentheses Perfection Kit containing different types of parentheses in the form of the string kitParentheses and their respective efficiency ratings in the efficiencyRatings array (both of size m). The EfficiencyScore of the original strings is initially 0. You can use any number of unused parentheses from the kit to create the final sequence, as long as the final sequence remains balanced. The task is to determine the maximum possible EfficiencyScore that can be achieved for the resulting balanced sequence. Note: It is guaranteed that the sequence can be made balanced by adding zero or more parentheses from the kit. Function Description Complete the function findMaxToBalance in the editor. findMaxToBalance has the following parameters:

    1. String s: the initial parentheses sequence
    1. String kitParentheses: the parentheses available in the kit
    1. int[] efficiencyRatings: the efficiency ratings of the parentheses in the kit Returns int: the maximum possible EfficiencyScore for the balanced sequence

Example 1

Input:

s = "()"
kitParentheses = "(())"
efficiencyRatings = [4, 2, -3, -3]

Output:

1

Explanation: If the user used the 0th indexed and 2nd indexed parentheses from the bag and add them to the start and end of the string respectively, then the final balanced sequence will be "(0)" with a total EfficiencyScore of 4 + (-3) = 1. There are no other combinations of adding parentheses that can yield a balanced sequence with total EfficiencyScore greater than 1, Hence return 1 as answer.

Example 2

Input:

s = "()"
kitParentheses = ")(()))"
efficiencyRatings = [3, 4, 2, -4, -1, -3]

Output:

6

Explanation: :)

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

A user is using the Amazon fitness tracker, and they are engaged in a jumping exercise routine. The user is positioned on the ground, and there are n stones, each placed at different heights. The height of the ith stone is represented by height[i] meters. The goal is to maximize the calorie burn during this exercise, and the calories burned when jumping from the ith stone to the jth stone is calculated as (height[i] - height[j])^2. The user intends to practice jumping on each stone exactly once but can choose the order in which they jump. Since the user is looking to optimize their calorie burn for this single session, the task is to determine the maximum amount of calories that can be burned during the exercise. Formally, given an array height of size n, representing the height of each stone, find the maximum amount of calories the user can burn. Note that the user can jump from any stone to any stone, and the ground's height is 0 and once user jumps to stone from ground, he/she can never go back to ground. Function Description Complete the function findMaximumCalories in the editor below. findMaximumCalories has the following parameters:

  • int height[n]: the height of each stone Returns long: the maximum amount of calories the user can burn.

Constraints

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

Amazon has a string of categories of items purchased by a particular customer, each represented as a lowercase English letter. To analyze customer behavior, we define a metric called the MaximaCount of a category. It is the number of indices where the frequency of some category c is maximum among all categories present in the prefix. More elaboratively, MaximaCount of character, char, representing a category is defined as the number of indices i, such that the frequency of char is maximal in the prefix of the string up to the index i. Given the string categories, find the maximum MaximaCount among all the categories. Function Description Complete the function findMaximumMaximaCount in the editor. findMaximumMaximaCount has the following parameter:

  • string categories: the given string Returns int: the maximum MaximaCount ⋆。 𓂃 𓈒𓏸˚ ゚1013rd thank you on the way to spike! ༊·˚

Constraints

  • The length(categories)

Example 1

Input:

categories = "bccaaacb"

Output:

6

Explanation: From the above table (assuming 1-based indexing): MaximaCount of a = 4 at indices 5, 6, 7, 8 MaximaCount of b = 2 at indices 1, 2 MaximaCount of c = 6 at indices 2, 3, 4, 5, 7, 8 Thus the maximum MaximaCount is 6 for the character c.

Example 2

Input:

categories = "zzzz"

Output:

4

Explanation: Since all characters in the string are equal, the maximum MaximaCount is 4 for the character z.

Example 3

Input:

categories = "adbcbcbcc"

Output:

6

Explanation: There are four different categories: [a,b,c,d] For a, we have a MaximaCount equal to 4 at indices 1, 2, 3, 4. For b, we have a MaximaCount equal to 6 at indices 3, 4, 5, 6, 7, and 8. For c, we have a MaximaCount equal to 4 at indices 4, 6, 8, and 9. For d, we have a MaximaCount equal to 4 at indices 1, 2, 3, 4.

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

In Amazon's financial team an analyst is dealing with an infinite number of bags arranged in a line, each numbered from 1 to infinity. The task is to gather information about the amount of money in these bags, presented in the form of continuous segments. The objective is to select consecutive bags in such a way that the total amount of money in these bags is maximized. The continuous segments provided to represent the amount of money in each bag do not intersect. Additionally, any bag included within a segment contains some amount of money, while bags not included in any segment are considered to have zero money. Formally, given a 2D array segment of size n x 3, where n represents the number of available segments, and an integer k representing the number of consecutive bags you will take, and the 2D array segment represents the range of bags included in this segment [segment[0], segment[1]] and the amount of money inside the bags in the range segment[2]. Find the k consecutive bags with the maximum total amount of money, since the answer can be large, return it modulo (10⁹ + 7). Function Description Complete the function findMaximumMoney in the editor. findMaximumMoney has the following parameters:

    1. int k: the number of consecutive bags you will take.
    1. int segment[n][3]: A 2D array where n is the number of segments. Each segment contains the start index, end index, and money in the bags for that range. Returns int: the amount of money inside the k consecutive bags with the maximum total amount of money modulo 10⁹ + 7.

Example 1

Input:

k = 5
segment = [[1, 4, 2], [6, 6, 5], [7, 7, 7], [7, 9, 1], [9, 10, 1]]

Output:

16

Explanation: The amount of money in each bag is: Bag 1 2 3 4 5 6 7 8 9 10 Money 2 2 2 2 0 5 7 0 1 1 All other bags have zero money. Let's try different consecutive bags of size k: Bags Total Money [1 - 5] 2 + 2 + 2 + 2 + 0 = 8 [2 - 6] 2 + 2 + 2 + 0 + 5 = 11 [3 - 7] 2 + 2 + 0 + 5 + 7 = 16 [4 - 8] 2 + 0 + 5 + 7 + 0 = 14 [5 - 9] 0 + 5 + 7 + 0 + 1 = 13 [6 - 10] 5 + 7 + 0 + 1 + 1 = 14 The subsegment starting from the third bag and ending at the seventh bag has the maximum total amount of money, hence the answer is 16.

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

Your team at AmzAn is building a quiz-style application to help students prepare for certification exams. Each quiz module tests one or more subjects and limits the number of review attempts each student has been asked to examine. To do this, please review each of the certification exams provide. You have within quiz modules answered[i] questions in each allows students to "pass" certain subjects with a total of q more questions overall. For each answer the following: Imagine a student has already answered needed[i] in order to pass. For each of the n subjects, and still has answered has to be at least pass if the q additional answered of the subject, the number of questions the student can pass determine the maximum number among the subjects. The questions are optimally distributed. For example, consider that there are n = 2 subjects and needed = [4, 5] answered questions, respectively, to pass. Imagine another q = 1 questions across all subjects combined. In that case, the best outcome is to answer an additional question in the second subject, in order to pass it, as 2 more answers are required to pass the first subject. The maximum number of subjects that can be passed is 1. Function Description Complete the function findMaximumNum in the editor below. The function must return an integer that represents the maximum number of subjects that can be passed. findMaximumNum has the following parameter(s):

  • int[] answered: an array of integers
  • int[] needed: an array of integers
  • int q: an integer

Constraints

  • 1 ≤ n ≤ 10⁵
  • 0 ≤ answered[i], needed[i], q ≤ 10⁹

Example 1

Input:

answered = [24, 27, 0]
needed = [51, 52, 100]
q = 100

Output:

2

Explanation: Here answered=[24,27,0] and needed=[51,52,100]. The additional answers needed to pass are [27,25,100]. The best distribution is at least 27+25=52 questions among the first two subjects. It would take all q=100 questions to pass the third subject.

Example 2

Input:

answered = [24, 27, 0]
needed = [51, 52, 100]
q = 200

Output:

3

Explanation: Explanation not found. If you happen to know about it, feel free to lmk! Manyyy thx in advance

Example 3

Input:

answered = [2, 4]
needed = [4, 5]
q = 1

Output:

1

Explanation: There are n = 2 subjects and needed = [4, 5] answered questions, respectively, to pass. The student has answered answered = [2, 4] questions in the two subjects so far, and can answer another q = 1 questions in all subjects combined. The best outcome is to answer an additional question in the second subject to pass it, and it is not possible to pass the first subject. The maximum num of subjects that can be passed is 1 :)

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

Given an array, the valid combinations are:

  • [3]
  • [6]
  • [3]
  • [3, 6, 3]
  • [6, 3]
  • [3, 6] A combination is considered balanced if the last element is not the largest value in that combination. For example, [3, 6, 3] is balanced because the last element (3) is not larger than the others. Your task is to find the maximum number of balanced combinations. A possible custom case you can use could be - input = [99,25,69,28,32] output = 8

Example 1

Input:

arr = [3, 6, 3]

Output:

2

Explanation: All possible combinations -

  • [3]
  • [6]
  • [3]
  • [3, 6, 3]
  • [6, 3]
  • [3, 6] Balanced if the last element in the combination is NOT the greatest value. Valid combinations - [3, 6, 3] --> 3 is not the greatest [6, 3] --> 3 is not the greatest
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given an array of products where each item is the quantity of some unique product, you need to ship these products in batches. The rules for creating a batch are as follows:

  • Each batch must contain only distinct products.
  • Each subsequent batch must contain strictly increasing number of distinct product types. Find the maximum number of batches that can be created. Function Description Complete the function findMaximumNumberOfBatches in the editor. findMaximumNumberOfBatches has the following parameter:
  • int[] products: an array of integers representing the quantity of each unique product Returns int: the maximum number of batches that can be created

Example 1

Input:

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

Output:

4

Explanation: The maximum number of batches that can be created from the given products is 4. The remaining products after each batch are as follows:

  • After the first batch: [2, 3, 4, 1, 1]
  • After the second batch: [1, 2, 4, 1, 1]
  • After the third batch: [1, 1, 3, 0, 1]
  • After the fourth batch: [0, 0, 2, 0, 0]
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

An AWS client wants to deploy multiple applications and needs two servers, one for their frontend and another for their backend. They have a list of integers representing the quality of servers in terms of availability. The client's preference is that the availability of an application's frontend server must be greater than that of its backend. Two arrays of same size s, frontend[s] and backend[s] where elements represent the quality of servers, create pairs of elements (frontend[i], backend[i]) such that frontend[i] > backend[i] in each pair. Each element from an array can be picked only once to form a pair. Find the maximum number of pairs that can be formed. Function Description Complete the function findMaximumPairs in the editor. findMaximumPairs has the following parameters:

  • int frontend[s]: frontend server qualities
  • int backend[s]: backend server qualities Returns int: the maximum number of pairs that can be formed

Constraints

  • 1 ≤ s ≤ 10⁵
  • 1 ≤ frontend[i], backend[i] ≤ 10⁹

Example 1

Input:

frontend = [1, 2, 3]
backend = [1, 2, 1]

Output:

2

Explanation: The possible valid pairs which can be made are:

  • (frontend[1], backend[0])=(2, 1) and (frontend[2], backend[2])=(3, 1) are valid pairs
  • (frontend[1], backend[0])=(2, 1) and (frontend[2], backend[1])=(3, 2) are valid pairs It can be seen that a maximum of 2 valid pairs can be made at a time. So the maximum number of pairs that can be formed is 2. Return 2.

Example 2

Input:

frontend = [1, 2, 3, 4, 5]
backend = [6, 6, 1, 1, 1]

Output:

3

Explanation: The valid pairs which we can form are as follows. (According to the given condition of frontend[i] > backend[i]):

  • (frontend[1], backend[2]) = {2,1}, (frontend[2], backend[3]) = {3,1} and (frontend[3], backend[4]) = {4,1} is one assignment to form pairs.
  • (frontend[1], backend[2]) = {2,1}, (frontend[2], backend[3]) = {3,1} and (frontend[4], backend[4]) = {5,1} is one assignment to form pairs.
  • (frontend[1], backend[2]) = {2,1}, (frontend[3], backend[3]) = {4,1} and (frontend[4], backend[4]) = {5,1} is one assignment to form pairs.
  • (frontend[2], backend[2]) = {3,1}, (frontend[3], backend[3]) = {4,1} and (frontends, backend[4]) = {5,1} is one assignment to form pairs. There are more valid assignment of pairs, but it can be made sure that there is no way we can create more than 3 pairs of assignment as among five elements of backend, two of them are 6 which is greater than the maximum value in frontend array. Hence return 3 as 3 is the maximum number of valid pairs that can be formed.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Data analysts at Amazon are analyzing a string, data. Each of its characters is worth 1 point. Any substring in which all characters are adjacent to characters within one position in the English alphabet is also worth 1 point. For example, "aa", "ab", and "ba" are each worth 1 point. To improve the score, at most one character can be replaced with any other character from the lowercase English alphabet. Given a string, data, find the maximum score that can be achieved.

Example 1

Input:

data = "aabacfgh"

Output:

21

Explanation: This test case was added on 06-05-2025. It was shared by a user friend in the Solution section, and I happen to come across it. I don’t know who you are, but thank you so much for sharing something so helpful! As alaways, relevant source ss is included in the Problem Source section :) The initial score is 17, one point for each of the 8 letters, and the following 9 substring contributing one point each: 'aa', 'ab', 'ba', 'aab', 'aba', 'aaba', 'fg', 'gh', 'fgh'. In the optimal scenario, change the character at the 5th position Le., data[4] = 'c'to 'b'. The string data becomes "aababfgh" and the score is thus calculated as: 1 point for each of the 8 letters of the string. The following substrings worth 1 point each: data[0:1] = "aa", data[0:2] = "aab", data[0:3] = "aaba", data[0:4] = "aabab". Total count = 4. data[1:2] = "ab", data[1:3] = "aba", data[1:4] = "abab". Total Count = 3. data[2:3] = "ba", data[2:4] = "bab". Total count = 2. data[3:4] = "ab". Total count = 1. data[5:6] = "fg", data[5:7] = "fgh", Total count = 2. data[6:7] = "gh". Total count = 1. Therefore, the total points is 8 +4+3+2+1+2+1=21. Hence, the answer is 21.

Example 2

Input:

data = "abcb"

Output:

10

Explanation: This test case was added on 06-05-2025. It was shared by a user friend in the Solution section, and I happen to come across it. I don’t know who you are, but thank you so much for sharing something so helpful! As alaways, relevant source ss is included in the Problem Source section :) The string is already in one of its most efficient forms, so no changes can increase Its score. A point is scored for 'a', 'b', 't,b Show Applications abc', 'bcb', and 'abcb'.

Example 3

Input:

data = "abez"

Output:

7

Explanation: "abez" to "abaz" Each of the substrings is worth 1 point. Hence, the final answer is 7.

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

In Amazon's financial team, an analyst is dealing with an infinite number of bags arranged in a line, each numbered from 1 to infinity. The task is to gather information about the amount of money in these bags, presented in the form of continuous segments. The objective is to select consecutive bags in such a way that the total amount of money in these bags is maximized. The continuous segments provided to represent the amount of money in each bag do not intersect. Additionally, any bag included within a segment contains some amount of money, while bags not included in any segment are considered to have zero money. Formally, given a 2D array segment of size n x 3, where n represents the number of available segments, and an integer k representing the number of consecutive bags you will take, and the 2D array segment represents the range of bags included in this segment [segment[0], segment[1]] and the amount of money inside the bags in the range segment[2]. Find the k consecutive bags with the maximum total amount of money, since the answer can be large, return it modulo (10⁹ + 7). Function Description Complete the function maxTotalAmount in the editor. maxTotalAmount has the following parameters:

    1. int[][] segment: a 2D array where each element is an array of three integers representing the range of bags and the amount of money
    1. int k: the number of consecutive bags Returns int: the maximum total amount of money in k consecutive bags, modulo (10⁹ + 7) ⸜(。˃ ᵕ ˂)⸝ Feeling so lucky to have spike's help~~

Example 1

Input:

segment = [[1, 4, 2], [6, 6, 5], [7, 7, 7], [9, 10, 1]]
k = 5

Output:

16

Explanation: The subsegment starting from the third bag and ending at the seventh bag has the maximum total amount of money, hence the answer is 16.

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

Given one unsorted array of size n and

Example 1

Input:

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

Output:

1

Explanation: Example - [1,4,3,6,5], k = 2, n-k = 3 Some Possible subequences of size 3 : [4,3,1] (sorted) -> [1,3,4] Diffs : 4-3 = 1, 3-1 = 1. Max of these is 1 [1,6,4] (sorted) -> [1,4,6] Diffs : 6-4 = 2, 4-1 = 3. Max of these is 3 [3,6,5] (sorted) -> [3,5,6] Diffs : 6-5 = 1, 5-3 = 2. Max of these is 2 Other subsequences follow.... Out of all possible sequences, we get the max diff in each subsequence. Out of these maxes find the minimum diff. In our case it's 1. Answer is 1

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

Amazon relies on a network of drones, each equipped with a unique carrying limit ranging from 1 to10⁹. The j-th drone can lift a max weight of j. The company must transport n shipments, where the weight of the i-th shipment is given by parcels[i]. During peak delivery periods, only two drones are available, and they must alternate their deliveries. This means that if Drone X delivers the i-thshipment, then Drone Y must handle the (i + 1)-th, and they must continue switching back and forth. However, some shipments may exceed a drone's capacity, making them undeliverable. To fix this, Amazon can swap certain shipments for ones with different weights to ensure that all deliveries are possible. Given that Amazon can select any two drones for this task, determine the minimum number of replacements required to successfully deliver all shipments. Function Description Complete the function findMinReplacements in the editor. findMinReplacements has the following parameter:

  • int parcels[n]: an array representing the weights of packages. Returns int: the minimum number of replacements needed.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

There were a large number of orders placed on Amazon Prime Day. The orders are packed and are at the warehouse ready to be delivered. The delivery agent needs to deliver them in as few trips as possible. In a single trip, the delivery agent can choose packages following either of two rules:

  • Choose two packages with the same weight
  • Choose three packages with the same weight Determine the minimum number of trips required to deliver the packages. If it is not possible to deliver all of them, return -1. Function Description Complete the function findMinTrips in the editor. findMinTrips has the following parameter:
  • int packageweight[n]: the weights of each package Returns int: the minimum number of trips required or -1 if it is not possible to deliver them all

Constraints

  • 1 ≤ n ≤ 10⁵⁵
  • 1 ≤ packageweight[i] ≤ 10⁹

Example 1

Input:

packageweight = [1, 8, 5, 8, 5, 1, 1]

Output:

3

Explanation: It takes 3 trips to deliver all the packages.

Example 2

Input:

packageweight = [3, 4, 4, 3, 1]

Output:

-1

Explanation: Packages with weights 3 and 4 can be removed in groups of two. The package of weight 1 cannot be delivered as it cannot be chosen according to the rules. Since it is not possible to deliver all packages, the answer is -1.

Example 3

Input:

packageweight = [2, 4, 6, 6, 4, 2, 4]

Output:

3

Explanation: The agent needs a min of 3 trips as shown above. Return 3 as the answer :)

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

Amazon's warehouse management team is planning to roll out certain standards and checks that every Amazon Warehouse Manager will follow. Some products may need to be moved initially from one warehouse to another so that each warehouse complies. A warehouse stores n identical containers arranged in the form of a circle. The distance between two adjacent containers is 1. Each container in a warehouse should hold the same number of products. Plan the optimal set of movements under the following rules. Move products from any location in either the clockwise or the anti-clockwise direction. The direction must remain the same throughout the remaining moves. While moving, collect excess products from some locations and deliver them to other locations that need more units. The cost of each product transfer is the distance the product is moved. The total cost is the sum of the costs for all products transferred. Find the minimum cost such that finally, every container has the same number of products. Note: In the examples, positions are one-indexed. It is guaranteed that it is always possible to distribute the products equally. Say TYVM to spike for the 1000 times!

Example 1

Input:

products = [3, 4, 6, 6, 6]

Output:

7

Explanation: Option 1 - Start at the 3^rd position and move clockwise. Collect one product each from the 3^rd, 4^th, and 5^th positions. Transfer the products from:

  • the 5^th position to the 1^st position, the cost is 1
  • the 4^th position to the 1^st position, the cost is 2
  • the 3^rd position to the 2^nd position, the cost is 4 Now each container has 5 units and the total cost is 1 + 2 + 4 = 7. Option 2 - Start at the 5^th position and move anti-clockwise. Collect one product each from the 5^th, 4^th, and 3^rd positions. Transfer the products from:
  • the 3^rd position to the 1^st position, the cost is 2
  • the 4^th position to the 1^st position, the cost is 3
  • the 5^th position to the 2^nd position, the cost is 3 Now each container has 5 units and the total cost is 2 + 3 + 3 = 8.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

A student is preparing for a scholarship test which is organized on the Amazon Academy platform and scheduled for next month. There are n chapters to be studied where the ith chapter has pages[i] pages. In one day, the student decides to read up to p of the remaining pages, each from some k consecutive chapters. Thus, the number of pages remaining to be read is reduced by p from each of these chapters. If a chapter has less than p pages remaining, the student reads the remaining pages, and the remaining page count is set to 0 for subsequent days. Find the minimum number of days the student needs to read all the chapters completely, i.e., the remaining page count of all chapters is 0. Note: The chapters read must be contiguous. Function Description Complete the function findMinimumDays in the editor below. findMinimumDays has the following parameters:

  • int pages[n]: the number of pages in each chapter
  • int k: the number of chapters chosen each day
  • int p: the maximum number of pages read from each chapter in a day Returns long int: the minimum number of days to read all pages of all chapters

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ pages[i] ≤ 10⁹
  • 1 ≤ k ≤ n
  • 1 ≤ p ≤ 10⁹

Example 1

Input:

pages = [3, 1, 4]
k = 2
p = 2

Output:

4

Explanation: The chapters can be read as follows:

  • Choose chapters 1 and 2, remaining pages to be read = [1, 0, 4]
  • Choose chapters 1 and 2, remaining pages to be read = [0, 0, 4]
  • Choose chapters 2 and 3, remaining pages to be read = [0, 0, 2]
  • Finally, choose chapters 2 and 3, remaining pages to be read = [0, 0, 0] The chapters cannot be read in less than 4 days.

Example 2

Input:

pages = [3, 4]
k = 1
p = 2

Output:

4

Explanation: Let's trace this sample case: Day 1: Choose chapter 1 (pages = 3). Read min(3,2)=2 pages. Remaining pages: [3−2,4]=[1,4]. Day 2: Choose chapter 1 (pages = 1). Read min(1,2)=1 page. Remaining pages: [1−1,4]=[0,4]. Day 3: Choose chapter 2 (pages = 4). Read min(4,2)=2 pages. Remaining pages: [0,4−2]=[0,2]. Day 4: Choose chapter 2 (pages = 2). Read min(2,2)=2 pages. Remaining pages: [0,2−2]=[0,0]. So, for this sample case, the minimum number of days would be 4. This test case is fromt the second source we found. You can find source ss from the second source images in the Problem Source section below.

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

note - See the Problem Source at the vely bottom of the page for the original problem description~ In a realm where data centers and servers flourished along a mystical one-dimensional line, a wise ruler sought to optimize their connections. Each data center needed to establish a bond with a server, minimizing the lag defined as the absolute distance between their coordinates. Tasked with this quest, the ruler gathered the bravest minds to decipher the best pairings from the enchanted positions of the data centers and servers. Together, they embarked on a journey to forge connections that would ensure the smallest lag possible, bringing harmony to the kingdom's network and enhancing its magical efficiency.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ center[i], destination[i] ≤ 10⁹

Example 1

Input:

center = [1, 2, 2]
destination = [5, 2, 4]

Output:

6

Explanation: In a land where three connections needed to be forged, the positions of the data centers were as follows: center = [1, 2, 2], while the server destinations were located at: destination = [5, 2, 4]. To achieve the most efficient deliveries, the following connections were made: a. The data center at location 1 established its first bond with the server at location 2. b. The data center at location 2 then connected to the server at location 4. c. Lastly, the other data center at location 2 formed a connection with the server at location 5. The minimum total lag for these connections was calculated as follows: abs(1 - 2) + abs(2 - 4) + abs(2 - 5) = 1 + 2 + 3 = 6. Thus, the quest for optimization was successful, with a total lag of 6 uniting the realm of data centers and servers.

Example 2

Input:

center = [3, 1, 6, 8, 9]
destination = [2, 3, 1, 7, 9]

Output:

5

Explanation: In a land filled with data centers and server destinations, a new set of connections needed to be established. The positions of the data centers were as follows: center = [1, 3, 6, 8, 9], and the server destinations were located at: destination = [1, 2, 3, 7, 9]. To create the most efficient connections, the following pairings were made: The data center at location 1 connected perfectly with the server at location 1. The data center at location 3 established a bond with the server at location 2. The data center at location 6 formed a connection with the server at location 3. The data center at location 8 connected to the server at location 7. Finally, the data center at location 9 paired with the server at location 9. The total distance for these connections was calculated as: abs(1 - 1) + abs(3 - 2) + abs(6 - 3) + abs(8 - 7) + abs(9 - 9) = 0 + 1 + 3 + 1 + 0 = 5. Thus, the quest for optimizing connections was accomplished with a minimum total distance of 5, ensuring harmony in the network of data centers and servers.

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

An analyst in the logistics team of Amazon e-commerce was reviewing the efficiency metrics of the new automated stocking and retrieval machines. They went about their calculations in the following manner: A sequence of n machines is tasked with stocking or retrieving items. Given the individual stocking/retrieving capacity values of each machine as an integer array, machineCapacity. The Efficiency of this sequence is evaluated using a comparison metric: the sum of the absolute difference between consecutive machine capacities. The task is to determine whether achieving the same sum of the absolute difference is possible by removing some machines from the sequence to streamline the operations. If it is possible, return the minimum number of machines required in the sequence to attain the same sum of the absolute difference between consecutive machine capacities. It's important to note that the number of machines in the sequence must always be greater than 0. If achieving the same sum is impossible on removal, return n, which is the original number of machines in the sequence. Note: The efficiency score of a sequence consisting of only one machine is 0. Function Description findMinimumMachinesSize() has the following parameter(s):

  • int machineCapacity[n]: the stocking/retrieval capacity of each machine Returns int: the minimum number of machines in the sequence required to achieve the same performance score Following is very likely a duplicate of this problem - Reasons for being duplicate - After comparing both problems, we are leaning toward (Find Minimum Machines Size) as the correct version. It seems likely that Minimize Array Differences was from memory, while Find Minimum Machines Size might’ve been copied more directly — which tends to be more reliable. Also, returning the number of operations (as in Find Minimum Machines Size) feels more aligned with what we typically see in these types of problems. And with the potential error in Example 2 of Minimize Array Differences that a pro pointed out, it just adds to the uncertainty around that version.

Constraints

  • 1 ≤ n ≤ 2*10⁵
  • 0 ≤ machineCapacity[i] ≤ 10⁹

Example 1

Input:

machineCapacity = [1, 2, 2, 1, 1]

Output:

3

Explanation: Efficiency initially: ∣1−2∣ + ∣2−2∣ + ∣2−1∣ + ∣1−1∣ = 2 Efficiency after removal of position [2],[3]: ∣1−2∣ + ∣2−1∣ = 2 It can be seen that after the removal of these 2 machines, we obtain the same efficiency. Thus, the answer in this case is 3. It can be proven that the answer can't be less than 3.

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

Within the Amazon Real Estate Analytics Toolset, an investor is evaluating a series of buildings of varying heights. The investor aims to find a group of buildings that adhere to two key conditions:

  • The selected buildings must form a valid group.
  • A group of buildings is considered valid if it meets the following criteria.
  • It is a contiguous subsegment of the original array with a size of at least 2.
  • The heights of the first and last buildings in this subsegment are the same.
  • The group variance should be as minimal as possible. The investor's goal is to find such a valid group of buildings with the minimal possible variance in height among the buildings in the group. The variance of a group is the difference between the size of the group and the occurrences of the first element height in the group, for example, the variance of the group (4, 2, 5, 4) is 4-2=2. Formally, given an array height of size n, the height of each building, find the minimum possible variance of a valid group of buildings, it is guaranteed that there is at least one valid group. An array a is a subsegment of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. for example, [3, 1], and [4] is a subsegment of array [1, 3, 1, 4] while [1, 1], and [1, 4] is not. spike is the supa hero!

Constraints

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

Some developers at Amazon are building a prototype for a simple rate-limiting algorithm. There are n requests to be processed by the server represented by a string requests where the ith character represents the region of the ith client. Each request takes 1 unit of time to process. There must be a minimum time gap of minGap units between any two requests from the same region. The requests can be sent in any order and there can be gaps in transmission for testing purposes. Find the minimum amount of time required to process all the requests such that no request is denied. Function Description Complete the function findMinimumTimeRequired in the editor. findMinimumTimeRequired has the following parameters:

    1. String requests: a string where each character represents the region of a client
    1. int minGap: the minimum time gap required between two requests from the same region Returns int: the minimum amount of time required to process all requests

Example 1

Input:

requests = "abacadaeafag"
minGap = 2

Output:

16

Explanation: One optimal strategy is "ab_ad_afgae_ac_a".

Example 2

Input:

requests = "aaabbb"
minGap = 0

Output:

6

Explanation: Since the minGap is 0, the requests can be processed in any order without any gaps.

Example 3

Input:

requests = "aaabbb"
minGap = 2

Output:

8

Explanation: The requests can be sent in order "ab_ab_ab" wher _ represents that no request was sent. Here, the min time gap between two requests from the same region is minGap = 2. The total time taken is 8 units :)

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

Amazon is introducing an innovative smart canvas display for personalized home decor. The canvas is initially painted white, featuring n rows and m columns, waiting to be transformed into a beautiful masterpiece. Each minute, the canvas undergoes a unique coloring process as specified by the user. A beautiful canvas is defined by the presence of a square with a side length of k where all cells within the square are elegantly colored. Determine the minimum time required for the canvas to achieve its beauty. Formally, Given n and m that denote the number of rows and columns of the canvas respectively, k denotes the size of the square, and a 2D array paint of dimensions (n * m) rows and 2 columns, where each entry (paint[i][0], paint[i][1]) represents the coordinates of a cell to be painted black during the ith minute. Note that each cell is painted only once during this transformation. Find the minimum time (in minutes) after which the canvas becomes beautiful.

Constraints

  • 1 ≤ n, m ≤ 750
  • 1 ≤ k ≤ min(n, m)
  • 1 ≤ paint[i][0] ≤ n
  • 1 ≤ paint[i][1] ≤ m
  • paint[i] ≠ paint[j] for any `1 ≤ i
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

In the context of an Amazon gaming product involving a snake and apples on a number line, the product simulates a set of unique coordinates representing the positions of the apples. The array named position of size n holds these unique integers, each denoting the coordinate of the nth apple. The snake, starting at the origin (0 coordinate), decides to consume some of the apples. The snake can move left and right along the line at a constant speed of 1 unit/sec, allowing it to transition from a coordinate x to y (or y to x) in |y - x| seconds. Additionally, the snake can instantly eat an apple when it occupies the same coordinate as the apple. Given an integer k and the array position, Determine the minimum time required for the snake to consume at least k apples. Function Description Complete the function findMinimumTime in the editor below. findMinimumTime has the following parameters:

    1. int n: the minimum number of apples the snake needs to eat
    1. int k
    1. int position[n]: an array of integers denoting the coordinates of the apples on the number line. Returns int: the minimum time required for the snake to eat at least k apples. 𓂃 𓈒𓏸 Much appreciated, HxyJxy and spike!𓂃

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ k ≤ n
  • | position[i]| ≤ 10⁸ OR −10⁸ ≤ position[i] ≤ 10⁸
  • The array position consists of distinct integers.

Example 1

Input:

n = 3
k = 3
position = [-20, 5, 10]

Output:

40

Explanation: It is optimal to choose the following way:

  • Initially, the snake is at coordinate 0. As the snake needs to eat all three apples,
  • It will first go right for 5 seconds and eat the apple at position 5.
  • It moves in the same direction for another 5 seconds to reach coordinate 10 and eat the apple there.
  • Now it moves left for 30 seconds to reach the coordinate -20 and eat the apple there. Time taken will be 5 + 5 + 30 = 40 seconds. It can be shown that it is not possible for the snake to eat all the apples in less than 40 seconds. Hence, the answer is 40.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

A digital commerce platform is conducting an experiment on the number of customer feedback entries associated with each item in its catalog. You are provided with an array feedback of size n, where feedback[i] denotes the current number of feedback entries for the i-th item. The platform offers API endpoints that allow modifying these counts by either increasing or decreasing them by one per call. Given an integer array targetCounts of size q, your task is to determine the number of API calls required to adjust the feedback count of every item in feedback so that all items match each value in targetCounts. The objective is to return an array of size q, where the i-th element represents the total number of API calls necessary to align all feedback counts with targetCounts[i]. Function Description Complete the function findNetworkCalls in the editor below. findNetworkCalls has the following parameters:

  • int feedback[n]: the initial count of reviews of each product
  • int targetCounts[q]: the equal count of reviews Returns long[]: an array where each element denotes the total API calls needed to align all feedback counts to the corresponding value in targetCounts

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ feedback[i] ≤ 10⁶
  • 1 ≤ q ≤ 10⁵
  • 1 ≤ targetCounts[i] ≤ 10⁶

Example 1

Input:

feedback = [4, 6, 5, 2, 1]
targetCounts = [3]

Output:

[10, 20]

Explanation: Answer Version 1 - Therefore, the total API calls made to change the number of reviews for all products to 3 is: 1 + 3 + 2 + 1 + 2 = 9. Hence, return the array [9]. Answer Version 2 (newly found on 03-31-2025) - The source indicates that the expected output for this test case is expected to be [10, 20]. As we can see, the table is not complete in the source found this time. I will update once find more complete source. As the screenshots were taken on the platform, our expected output will go with [10, 20].

Example 2

Input:

feedback = [3, 6, 6]
targetCounts = [5, 6]

Output:

[4, 3]

Explanation: For counts value 5 - The total number of API calls to be made is 2 + 1 + 1 = 4. For counts value 6 - The total number of API calls to be made is 3 + 0 + 0 = 3. So, we return [4, 3]. P.s. This new test was added on 03-31-2025. Relevant source image was included in the Problem Source section below.

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

Amazon's product recommendation system aims to suggest relevant products to customers based on their recent purchase history. To achieve this, we need to identify substrings within a customer's purchase history that can be formed by concatenating all the available products in any order. We refer to such substrings as "compatible" substrings. A substring of the purchase history is considered "compatible" if it can be formed by concatenating all the available products in any order, regardless of the order of concatenation. Given n products, string history, and an array of string products, find the number of compatible substrings of history. Note: All the strings in products are of equal length. Each available product must be concatenated exactly once in any order to check for compatibility. The array products might contain duplicate products as well. In that case, each of the products (including duplicates) must be concatenated exactly once in any order as per the above rule. Function Description Complete the function findNumberOfCompatibleSubstrings in the editor. findNumberOfCompatibleSubstrings has the following parameters:

  • String history: the purchase history
  • String[] products: an array of product strings Returns int: the number of compatible substrings

Example 1

Input:

history = "abcdefdefabcghidefabcxyz"
products = ["abc", "def", "ghi"]

Output:

3

Explanation: There are 3 substrings in history, that are compatible strings. The first substring "defabcghi", can be formed by concatenation of the available products in the following order [1, 0, 2] i.e.. by "def" + "abc" + "ghi" = "defabcghi". Hence, this substring is "compatible". The second substring "abcghidef", can be formed by concatenation of the available products in the following order [0, 2, 1] i.e.. by "abc" + "ghi" + "def" = "abcghidef". Hence, this substring is "compatible". The third substring "ghidefabc", can be formed by concatenation of the available products in the following order [2, 1, 0] i.e., by "ghi" + "def" + "abc" "ghidefabc". Hence, this substring is "compatible". No other substrings can be obtained by concatenating the products in any order. Hence, the answer is 3.

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

Given a string of lowercase characters, pick substring of any length in it and reverse them. Find the number of possible unique strings. Function Description Complete the function findNumberOfPossibleUniqueStrings in the editor. findNumberOfPossibleUniqueStrings has the following parameter: String s: the input string Returns int: the number of possible unique strings

Constraints

  • The length of the input string is 1 to 10⁵

Example 1

Input:

s = "abc"

Output:

4

Explanation: Possible unique strings: Substring of length 1: Reversing a single character results in same original string. For example reverse a in abc, gives abc Substring of length 2: Reverse ab (substring of length 2) in abc results in bac Reverse bc (substring of length 2) in abc results in acb Substring of length 3: Reverse abc (substring of length 3) in abc results in cba So return result as 4

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

In one of the warehouses of Amazon, a pan balance is used to weigh and load the parcels for delivery. A pan balance has 2 pans, and each of the pans can contain one parcel. Due to some defect, one of the pans shows an extra erroneous weight wt. A pair of parcels is said to be balanced if they show the same weight on the pan balance. Since one of the pans is heavier by the amount wt, the absolute difference in weight of the parcels has to be wt. Given the weights of n parcels, weight[n], and the erroneous weight wt, find the number of ways to group these parcels into pairs such that every pair of the group is balanced. Since the answer can be large, compute it modulo (10⁹ + 7). Technically, the task is to find out the number of pairs that can be formed from the weight array which have an absolute difference equal to wt. If there are no such pairs, you have to return 0. Note:

  • A parcel cannot be present in more than one pair in a group.
  • Two groups are different if at least one of their pairs contains a different pair of parcels. The pairs at indices (i, j) and (j, i) are considered the same.
  • If there are no such pair, you have to return 0. Function Description Complete the function numberOfWaysToGroupParcels in the editor. numberOfWaysToGroupParcels has the following parameters:
  • int weight[n]: an array of integers representing the weights of the parcels
  • int wt: the erroneous weight shown by one of the pans Returns int: the number of ways to group the parcels into balanced pairs modulo (10⁹ + 7)

Constraints

  • 1 ≤ n ≤ 10⁵
  • 0 ≤ wt ≤ 10⁹
  • 1 ≤ weight[i] ≤ 10⁹

Example 1

Input:

weight = [4, 5, 5, 4, 4, 5, 2, 3]
wt = 1

Output:

6

Explanation: Pairs will contain either 4 and 5 or 2 and 3 with an absolute difference of 1. All possible ways of grouping the parcels into pairs are, {(1, 2), (4, 3), (5, 6), (7, 8)}, {(1, 3), (4, 2), (5, 6), (7, 8)}, {(1, 6), (4, 3), (5, 2), (7, 8)}, {(1, 2), (4, 6), (5, 3), (7, 8)}, {(1, 3), (4, 6), (5, 2), (7, 8)} and {(1, 6), (4, 2), (5, 3), (7, 8)}. In all these groups, the absolute difference of the weights of each pair of parcels is equal to the given extra weight wt = 1. For example, consider the group {(1, 6), (4, 2), (5, 3), (7, 8)}.

  • |weight[1] - weight[6]| = |4 - 5| = 1
  • |weight[4] - weight[2]| = |4 - 5| = 1
  • |weight[3] - weight[5]| = |5 - 4| = 1
  • |weight[7] - weight[8]| = |2 - 3| = 1
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

In order to ensure maximum security, the developers at Amazon employ multiple encryption methods to keep user data protected. In one method, numbers are encrypted using a scheme called 'Pascal Triangle'. When an array of digits is fed to this system, it sums the adjacent digits. It then takes the rightmost digit (least significant digit) of each addition for the next step. Thus, the number of digits in each step is reduced by 1. This procedure is repeated until there are only 2 digits left, and this sequence of 2 digits forms the encrypted number. Given the initial sequence of the digits of numbers, find the encrypted number. You should report a string of digits representing the encrypted number. Function Description Complete the function findNumber in the editor. findNumber has the following parameter:

  • int numbers(n): the initial sequence of digits Returns string: the encrypted number represented as a string of 2 characters. spike carries!

Constraints

  • 2 ≤ numbers.length ≤ 5 · 10³
  • 0 ≤ numbers[i] ≤ 9

Example 1

Input:

numbers = [4, 5, 6, 7]

Output:

"04"

Explanation: Encryption occurs as follows: Hence, the encrypted number formed is 04.

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

Amazon developers are creating a new security module for Amazon Web Services. One of its functions is to obfuscate incoming messages. The obfuscation method is to select some substring of the message and right rotate that substring by 1 position one time only. The substring is selected in such a way that the resulting obfuscated message is alphabetically the smallest message that can be formed using this operation. Here, right rotating any string by 1 position is to shift every character of string a in the right direction by 1 position and remove the last character and append it to the beginning of string a. For example, a = "ahssd", after right rotation by 1 position string a changes to "dahss". Given the input message as a string, find the obfuscated message. Note: A string x is alphabetically smaller than string y, if either x is a prefix of y (and x ≠ y), or there exists such i (0 ≤ i Function Description Complete the function findObfuscateMessage in the editor below. findObfuscateMessage has the following parameter:

  • string message: the input message Returns string: the encrypted message Image source will be attached in next update...

Constraints

  • 1 ≤ |message| ≤ 10⁵
  • The string message contains only lower case English letters.

Example 1

Input:

message = "aahhab"

Output:

"aaahhb"

Explanation: These are some of the possible strings. Rotating the substring "hha" produces "ahh". Replace "hha" in the original string to get "aaahhb", the alphabetically smallest message that can be formed. Return "aaahhb".

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

Amazon is dedicated to leveraging advanced methods to streamline stock movement across its distribution centers. In this scenario, you are assigned a challenge involving a specific process with a sequence of stock quantities. More specifically, you are provided with an array of positive numbers, stockArr, containing n elements. Additionally, you are given two positive numbers, incVal and decVal, where incVal is less than or equal to decVal. You may execute the stock adjustment operation on stockArr any number of times, including not performing it at all. The stock adjustment operation is defined as picking two distinct positions p and q in the array (0 ≤ p, q < n), increasing the value at stockArr[p] by incVal, and decreasing the value at stockArr[q] by decVal. Our goal is to compute the highest achievable value of the minimum stock quantity in stockArr after completing all desired operations. Note: During the adjustment process, some elements may become negative. However, once all operations have been completed, every number in stockArr must be strictly greater than 0.

Constraints

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

The database specialists at Amazon are engaged in segmenting their sequence of interconnected servers. There exists a consecutive sequence of m servers, labeled from 1 to m, where the expense metric linked to the j-th server is given in the list expense[j]. These servers must be divided into precisely p separate server segments. The expense of dividing a server segment from servers[x : y] is established as expense[x] + expense[y]. The aggregate expense accounts for the sum of partitioning costs for all server segments. Given m servers, a list expense, and an integer p, determine both the least and greatest achievable total expense of these operations and return them as a list of length 2: [minimum expense, maximum expense]. Note: Splitting a list means dividing it into consecutive subsequences where each item belongs strictly to one segment. For a list [10, 20, 30, 40, 50], a valid segmentation would be [[10], [20, 30], [40, 50]], while [[10, 20], [20, 30], [40, 50]] and [[10, 30], [20, 40, 50]] would be deemed incorrect .

Example 1

Input:

expense = [1, 2, 3, 2, 5]
p = 3

Output:

[14, 18]

Explanation:

Example 2

Input:

expense = [1, 2, 3, 4]
p = 2

Output:

[12, 8]

Explanation: Answer : Max = 12 [1+3,4+4] First Partition Is From Index 0 To 2 , second From 3 To 3 Min = 8 [1+1,2+4] First Partition From Index 0 to 0 , second From 1 To 3 PPS: This test case was added on 03-28-2025. Relevant source ss was included in the Problem Source section below.

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

Hello! Did you navigate here from my sister question Password Strength ? Another check pwd strength question you might be interested in: Find the password strength for a given password. For example, if the password is "good", then iterate over all substrings and find the distinct character counts:

  • g = 1,
  • o = 1,
  • o = 1,
  • d = 1,
  • go = 2,
  • oo = 1,
  • od = 2,
  • goo = 2,
  • ood = 2,
  • good = 3 At the end, add all the distinct character counts to determine the password strength. In this case, the password strength is 16. Function Description Complete the function findPasswordStrength in the editor. findPasswordStrength has the following parameter:
  • String password: the password string Returns int: the password strength

Example 1

Input:

password = "good"

Output:

16

Explanation: Iterate over all substrings and find the distinct character counts:

  • g = 1,
  • o = 1,
  • o = 1,
  • d = 1,
  • go = 2,
  • oo = 1,
  • od = 2,
  • goo = 2,
  • ood = 2,
  • good = 3 The total strength is the sum of all distinct character counts: 1 + 1 + 1 + 1 + 2 + 1 + 2 + 2 + 2 + 3 = 16.

Example 2

Input:

password = "aa"

Output:

2

Explanation: Iterate over all substrings and find the distinct character counts: "a" "a" "aa" We return 2 because both "a" and "a" have dictinct character counts of 1. 1 + 1 = 2 This case was added on 03-22-2025 :) Here is the source img -

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

Amazon rewards its new users with a discount coupon that can be applied to their first purchase. Some users create more than one account in order to receive the offer multiple times. It was found that their new usernames are only a permutation of their real names. For examples, if the real usernames of the users are realNames = ["abc", "def"] and the list of all usernames is allNames = ["bca", "abc", "cba", "def"], then the user "abc" must have made multiple accounts as there are three permutations of "abc" in the list of all usernames. Given an array of realNames an array allNames of usernames for each account, identify the names of users who created accounts more than once. The goal is to return the array of real names of these users in lexicographical order. If there are no such names, return an array containing only the string "None". Please note that: It is guaranteed that no two real names are permutations of each other. For the variable realNames, each value is unique, and indicates an individual person. Each name in allNames is a permutation of some name in realNames. There may be some names in realNames without a permutation in allNames. It is possible that some users may create an account using fake names only. Function Description Complete the function findRecurringNames in the editor. findRecurringNames has the following parameters:

  • string realNames[n]: the real user names
  • string allNames[m]: all registered user names Returns string[]: the distinct real names of users with multiple registrations in lexicographical order

Constraints

  • 1 ≤ n, m ≤ 10⁵
  • 1 ≤ |realNames[i]|, |allNames[i]| ≤ 10
  • Each name in realNames and allNames consists of lowercase English letters only.

Example 1

Input:

realNames = ["rohn", "henry", "daisy"]
allNames = ["ryhen", "aisyd", "henry"]

Output:

["henry"]

Explanation: "henry" occurs twice, as "ryhen" and "henry". A permutation of "daisy" occurs once and there are no permutations of "rohn".

Example 2

Input:

realNames = ["tom", "jerry"]
allNames = ["reyjr", "mot", "tom", "jerry", "mto"]

Output:

["jerry", "tom"]

Explanation: "tom" occurs thrice as "mot", "tom", and "mto". "jerry" occurs twice as "reyjr" and "jerry".

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

Amazon Web Services (AWS) is a cloud computing platform with multiple servers. One of the servers is assigned to serve customer requests. There are n customer requests placed sequentially in a queue, where the ith request has a maximum waiting time denoted by wait[i]. That is, if the ith request is not served within wait[i] seconds, then the request expires and it is removed from the queue. The server processes the request following the First In First Out (FIFO) principle. The 1st request is processed first, and the nth request is served last. At each second, the first request in the queue is processed. At the next second, the processed request and any expired requests are removed from the queue. Given the maximum waiting time of each request denoted by the array wait, find the number of requests present in the queue at every second until it is empty. Note: If a request is served at some time instant t, it will be counted for that instant and is removed at the next instant. The first request is processed at time = 0. A request expires without being processed when time = wait[i]. It must be processed while time The initial queue represents all requests at time = 0 in the order they must be processed. Function Description Complete the function findRequestsInQueue in the editor. findRequestsInQueue has the following parameter:

  • int wait[n]: the maximum waiting time of each request Returns int[]: the number of requests in the queue at each instant until the queue becomes empty.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ wait[i] ≤ 10⁵

Example 1

Input:

wait = [2, 2, 3, 1]

Output:

[4, 2, 1, 0]

Explanation:

  • time = 0 seconds, the 1st request is served. The number of requests in the queue is 4. queue = [1, 2, 3, 4].
  • time = 1 second, request 1 is removed because it is processed, request 4 (wait[3] = 1) is removed because time = wait[3] = 1 which exceeds its maximum waiting time. Also, request 2 is served. The number of requests in the queue at time = 1 seconds is 2. queue = [2, 3].
  • time = 2 seconds, request 2 is removed because it is processed, request 3 is served. The number of requests in the queue is 1. queue = [3].
  • time = 3 seconds, request 3 is removed because it is processed. The number of requests in the queue is 0. queue = [empty]. The answer is [4, 2, 1, 0].

Example 2

Input:

wait = [4, 4, 4]

Output:

[3, 2, 1, 0]

Explanation:

  • time = 0 seconds, request 1 is served. queue = [1, 2, 3]
  • time = 1 second, request 1 is removed as it is processed, request 2 is served. queue = [2, 3]
  • time = 2 seconds, request 2 is removed as it is processed, request 3 is served. queue = [3]
  • time = 3 seconds, request 3 is removed as it is processed. queue = [empty] so the answer is [3, 2, 1, 0]~~

Example 3

Input:

wait = [3, 1, 2, 1]

Output:

[4, 1, 0]

Explanation:

  • time = 0 secons, request 1 is served. The num of requests in queue is 4. queue = [3, 1, 2, 1]
  • time = 1 second, request 1 is removed as it is processed, request 2 and 4 are removed as time exceeds their max wating time , which is wait[1] = wait[3] = 1. Finally request 3 is served . The num of requests in the queue is 1. queue = [3]
  • time = 2 seconds, request 3 is removed as it is processed. The num of requests in the queue is 0, queue = [empty] so the answer is [4, 1, 0]~
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Source said that the other problem in the same batch was for Newe Grad, so I assume this problem is for New Grad as well.

  • Segmentify: Minimum Subsegments Amazon is launching a revolutionary security feature that incorporates an advanced antivirus program, adept at identifying and halting potential threats. This framework manages n active programs, each with a unique Program Identifier (PID). The antivirus program evaluates the overall security risk of the system using a specialized algorithm. • The algorithm analyzes contiguous subarrays of Program Identifiers (PIDs) represented by the array pid. • For each subarray, it calculates the sum of the PIDs and divides this sum by a given integer k. • The remainder obtained from this division is compared to the number of programs in the subarray. • A subarray is flagged if the remainder equals the number of programs within it and is considered as malicious. • The overall security risk is determined by the total count of such flagged subarrays. Formally, given an array pid of size n, representing the PIDs of the programs running on the computer, and an integer k, with which remainder has to be checked. The task is to calculate the system's security risk level. Note: • Remainder is defined as the remaining part after performing the division. For example, the remainder of 13 with 5 is 3. • A subarray is a continuous portion of an array. For example, in the array [5, 7, 9, 11], possible subarrays include [5, 7], [7, 9, 11], [11] etc. Note that a subarray maintains the original order of elements and consists of consecutive elements. Function Description Complete the function findSecurityLevel in the editor. findSecurityLevel has the following parameters:
  • int pid[n]: an array of integers denoting the PIDs of the programs
  • int k: an integer with which remainder is checked Returns long: an integer denoting the overall security risk of the system

Constraints

  • 1 ≤ n ≤ 2×10⁵
  • 1 ≤ pid[i] ≤ 10⁹
  • 1 ≤ k ≤ 10⁹

Example 1

Input:

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

Output:

2

Explanation: There are 2 different malicious contiguous subarrays:

  • Subarray from index [0, 0] with pid given by: [1], the remainder of the sum of pid sum = 1 of the subarray (1) with k = 4 is 1, the remainder of 1 with 4 is 1, which is equal to the number of elements in the subarray, i.e., 1. Hence, this subarray is flagged.
  • Subarray from index [2, 3] with pid given by: [2, 4], the remainder of the sum of pid sum = 2 + 4 = 6 of the subarray with k = 4 is 2, which is equal to the number of elements in the subarray, i.e., 2. Hence, this subarray is flagged. An example of a contiguous subarray is which is not flagged:
  • Subarray from index [0, 1] with pid given by: [3, 2] is not flagged because the remainder of the sum of PIDs = 3 + 2 = 5, whose remainder with k = 4 is 1, while there are 2 elements in the subarray. Hence, the subarray is not malicious. Hence, the overall security risk of the system is 2. Thus, return 2 from the function.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given an array of integers and two specified numbers, find a subarray from the original array that contains both of these specified numbers, with the requirement that the subarray contains the minimum number of distinct numbers. Return the count of distinct numbers in this subarray. If the two specified numbers are the same, simply return 1 if the array contains this number, otherwise return 0. Function Description Complete the function findSubarrayWithMinimumDistinctIntegers in the editor. findSubarrayWithMinimumDistinctIntegers has the following parameters:

    1. int[] array: an array of integers
    1. int series1: the first specified number
    1. int series2: the second specified number Returns int: the count of distinct numbers in the subarray

Example 1

Input:

array = [1, 2, 2, 2, 5, 2]
series1 = 1
series2 = 5

Output:

3

Explanation: The subarray must contain the series1 and series2 and having the smallest number of distinct values is [1, 2, 2, 2, 5], so return 3, the number of distinct integers in this subarray.

Example 2

Input:

array = [1, 3, 2, 1, 4]
series1 = 1
series2 = 2

Output:

2

Explanation: The shortest subarray contains both series1 and series2 is [2, 1], so we return 2, the number of distinct values in this subarray.

Example 3

Input:

array = [3, 1, 2]
series1 = 1
series2 = 1

Output:

1

Explanation: Because series1 and series2 are the same, so if the array contains series1, that would be good. This array contains series1, so we return 1.

Example 4

Input:

array = [2, 4, 9]
series1 = 1
series2 = 1

Output:

0

Explanation: Because series1 and series2 are the same, but this array doesn't contain series1, so we return 0.

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

Amazon's development team is working on a feature for a new product, a smart array processor. A user has provided an integer array called arr of size n and a 2-dimensional array called pairs of size m x 2. Each pair in pairs represents the starting and ending indices of a subarray within arr. For each subarray of arr represented by the array pairs, the goal is to merge and concatenate them into a new array called beautiful. The beauty of an element at index i in arr is defined as follows: if the index i has not contributed to the formation of the array beautiful, the beauty is the count of integers in beautiful that have a value strictly smaller than arr[i]. If the index i has contributed to the formation of the array beautiful, its beauty is 0. Find the sum of the beauties of all the elements in the array arr.

Example 1

Input:

arr = [1, 2, 3, 2, 4, 5]
pairs = [[0, 1], [3, 4], [0, 0], [3, 4]]

Output:

9

Explanation: Note - Not entirely sure about the explanation and the example output of 9. If you find any mistakes, pls feel free to lmk! I am more than happy to fix it!! I will add more info once I find more clarity / references of this problem! Extract the subarrays based on the pairs and concatenate them into the beautiful array: From pair [0, 1], extract subarray arr[0:2] = [1, 2]. From pair [3, 4], extract subarray arr[3:5] = [2, 4]. From pair [0, 0], extract subarray arr[0:1] = [1]. From pair [3, 4] (again), extract subarray arr[3:5] = [2, 4]. Now, concatenate all these subarrays to form beautiful: beautiful = [1, 2, 2, 4, 1, 2, 4] Identify the indices of the elements in arr that contribute to beautiful: From pair [0, 1], indices 0 and 1 contribute. From pair [3, 4], indices 3 and 4 contribute. From pair [0, 0], index 0 contributes. From pair [3, 4] again, indices 3 and 4 contribute. Therefore, the contributing indices are: 0, 1, 3, 4. These elements from arr have already been included in beautiful. Calculate the beauty of each element in arr: Element at index 0 (arr[0] = 1): Already included in beautiful, so its beauty is 0. Element at index 1 (arr[1] = 2): Already included in beautiful, so its beauty is 0. Element at index 2 (arr[2] = 3): Not included in beautiful. The beauty of arr[2] is the count of elements in beautiful that are strictly smaller than 3. In beautiful = [1, 2, 2, 4, 1, 2, 4], we have 3 elements smaller than 3 (the 1, 2, 2). Therefore, its beauty is 3. Element at index 3 (arr[3] = 2): Already included in beautiful, so its beauty is 0. Element at index 4 (arr[4] = 4): Already included in beautiful, so its beauty is 0. Element at index 5 (arr[5] = 5): Not included in beautiful. The beauty of arr[5] is the count of elements in beautiful that are strictly smaller than 5. In beautiful = [1, 2, 2, 4, 1, 2, 4], we have 6 elements smaller than 5 (all except 5 itself). Therefore, its beauty is 6. Sum the beauties of all elements: Beauty of arr[0] = 0 Beauty of arr[1] = 0 Beauty of arr[2] = 3 Beauty of arr[3] = 0 Beauty of arr[4] = 0 Beauty of arr[5] = 6 Total beauty = 0 + 0 + 3 + 0 + 0 + 6 = 9. Final Output: The sum of beauties is 9.

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

There are n developers working at Amazon where the i^th developer has the experience points experience[i]. The company decided to pair the developers by iteratively pairing the developers with the highest and lowest remaining experience points for a hackathon. The combined experience of a pair is the average of the experience points of the two developers. Find the number of unique values among the combined experience of the pairs formed. Function Description Complete the function findUniqueValues in the editor below. findUniqueValues has the following parameter:

  • int experience[n]: the experience points for each developer Returns int: the number of unique values among the combined experience points of the pairs formed

Constraints

1 n is an even number 1 ≤ esperience[i] ≤ 10⁹

Example 1

Input:

experience = [1, 4, 1, 3, 5, 6]

Output:

2

Explanation: There are n = 6 developers. The pairs formed are (1, 6), (1, 5), and (4, 3) making their experience points 3.5, 3, and 3.5 respectively. There are 2 distinct values, 3 and 3.5, so return 2 as the answer.

Example 2

Input:

experience = [1, 1, 1, 1, 1, 1]

Output:

1

Explanation: The developers will be paired up as follows (by index): (0, 1), (2, 3), and (4, 5). Each pair has a combined experience of 1.

Example 3

Input:

experience = [1, 100, 10, 1000]

Output:

2

Explanation: The developers are paired as follows (by index): (0, 3), (1, 2). The pairs have combined experience points of 500.5, and 55 respectively.

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

You are given an integer, requests which denotes the number of requests, and a list wait_time, where wait_time[i] denote the maximum wait time of the i'th request. The requests in the list are served from the first index to the last, and each request will be served for one second, then it is removed from the list (essentially, when you are at index 0, your current time is 0 seconds, then you spend 1 second serving request 0 and remove it from the list). Meanwhile, if some requests in the rest of the list to the right of the current request exceeds its wait time, then it is removed from the list as well. Return an array denoting how many active requests are present in the list each second.

Constraints

N/A

Example 1

Input:

requests = 6
wait_time = [5, 2, 2, 4, 7, 1]

Output:

[6, 4, 2, 2, 1, 0]

Explanation: N/A for now Will add once find it If you happen to know about it, pls feel free to tell me You da best!

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

Data analysts at Amazon are analyzing time-series data. It was concluded that the data of the n^th item was dependent on the data of some x^th day if there is a positive integer k such that floor(n / k) = x where floor() represents the largest integer less than or equal to z. Given n, find the sum of all the days' numbers on which the data of the x^th (0 ≤ x Function Description Complete the function getDataDependenceSum in the editor below. getDataDependenceSum takes the following arguments:

  • long int n: the day to analyze the data dependency for Returns long int: the sum of days on which the data is dependent Input Format For Custom Testing The first line contains a long integer, n. , As always, a supa huge TY to tomtom, spike and aikay! You three da best 4ever!!

Constraints

1 ≤ n ≤ 10¹⁰

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

A financial strategist at Amazon Web Services (AWS) is analyzing a collection of profitable investments, each represented by an integer array. Every value in the array indicates the annual gain of a particular investment. The strategist's goal is to identify all unique investment pairs whose combined annual returns exactly match a given target value. Unique pairs are defined as combinations that vary by at least one element (i.e., their values are not at the exact same positions or do not have identical values in identical positions). Given the array of gains, compute the number of unique investment pairs whose sum equals the specified target return. Function Description Complete the function getDistinctPairs in the editor. getDistinctPairs has the following parameter(s):

    1. int investmentReturns[n]: an array of integers representing each investment’s yearly gain
    1. goal: an integer denoting the targeted combined return Returns int: the total number of unique pairs that meet the target return

Constraints

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

Note --> Feel free to check the source image below for the original problem statement :) At a bustling tech company, there are n developers, each with their own set of experience points. The company is gearing up for an exciting hackathon and has come up with a unique way to form pairs of developers for the event. Their plan is to create pairs by matching the developer with the highest experience points with the one with the lowest experience points, and then move inward from both ends. As the developers are paired, the company is interested in analyzing the combined experience of each pair. The combined experience of a pair is calculated as the average of the experience points of the two developers. Your challenge is to determine how many unique values there are among these combined experience points. In simpler terms, given the list of experience points for all developers, you need to find out how many distinct average values result from pairing the highest and lowest remaining experience points iteratively.

Constraints

  • 2 ≤ n ≤ 10⁵
  • 0 ≤ exp[i] ≤ 10⁹
  • n is an even number

Example 1

Input:

exp = [1, 4, 1, 3, 5, 6]

Output:

2

Explanation: Imagine a company with 6 talented developers, each with their own unique set of experience points. As part of an exciting hackathon, the company decides to pair up these developers in a special way. They start by pairing the developer with the highest experience points with the one with the lowest experience points, then continue this process with the remaining developers, moving inward from both ends. For this example, the pairs formed are as follows: The developer with the highest experience points pairs with the one with the lowest: (1, 6). Next, the remaining developers are paired: (1, 5). Finally, the last pair is (4, 3). When calculating the combined experience for each pair, they find the following averages: Pair (1, 6) has a combined experience of 3.5. Pair (1, 5) has a combined experience of 3. Pair (4, 3) also has a combined experience of 3.5. So, among the combined experience values, there are 2 distinct values: 3 and 3.5. Your task is to determine the number of these unique combined experience values, which in this case is 2.

Example 2

Input:

exp = [1, 1, 1, 1, 1, 1]

Output:

1

Explanation: Here’s a storytelling version of the example with developers paired by their indices: In a tech company, there are 6 skilled developers, each with a certain amount of experience. As the company prepares for a hackathon, they decide to pair up the developers in a systematic manner: the first developer pairs with the second, the third with the fourth, and the fifth with the sixth. Here's how the pairs are formed: The first pair consists of developers at indices 0 and 1. The second pair consists of developers at indices 2 and 3. The third pair consists of developers at indices 4 and 5. Each pair's combined experience is calculated by averaging the experience points of the two developers. In this case, every pair ends up with a combined experience of 1. After calculating the combined experiences for all pairs, you find that there's only 1 unique value among them: 1. Thus, the number of distinct combined experience values is 1.

Example 3

Input:

exp = [1, 100, 10, 1000]

Output:

2

Explanation: The In a vibrant tech company, 4 developers are gearing up for a hackathon. To make things interesting, the company decides to pair them up in a unique way. They match the developer at index 0 with the one at index 3, and the developer at index 1 with the one at index 2. Here’s how the pairs are formed: The first pair consists of the developers at indices 0 and 3. The second pair consists of the developers at indices 1 and 2. After calculating the combined experience for each pair, you get: The combined experience for the pair (0, 3) is 500.5. The combined experience for the pair (1, 2) is 55. When you look at these combined experience values, you find that there are 2 distinct values: 500.5 and 55. Thus, the number of unique combined experience values among the pairs is 2.

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

Amazon stores its data on different servers at different locations. From time to time, due to several factors, Amazon needs to move its data from one location to another. This challenge involves keeping track of the locations of Amazon's data and reporting them at the end of the year. At the start of the year, Amazon's data was located at n different locations. Over the course of the year, Amazon's data was moved from one server to another m times. Precisely, in the ith operation, the data was moved from movedFrom[i] to movedTo[i]. Find the locations of the data after all m moving operations. Return the locations in ascending order. Note:

  • It is guaranteed that for any movement of data: There is data at movedFrom[i]. There is no data at movedTo[i]. Function Description Complete the function getFinalLocations in the editor. The function is expected to return an INTEGER_ARRAY. The function accepts the following parameters:
  • INTEGER_ARRAY locations
  • INTEGER_ARRAY movedFrom
  • INTEGER_ARRAY movedTo
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Alexa is Amazon's virtual AI assistant. It makes it easy to set up your Alexa-enabled devices, listen to music, get weather updates, and much more. The team is working on a new feature that evaluates the aggregate temperature change for a period based on the changes in temperature of previous and upcoming days. Taking the change in temperature data of n days, the aggregate temperature change evaluated on the i^th day is the maximum of the sum of the changes in temperatures until the i^th day, and the sum of the change in temperatures in the next (n - i) days, with the i^th day temperature change included in both. Given the temperature data of n days, find the maximum aggregate temperature change evaluated among all the days. Function Description Complete the function getMaxAggregateTemperatureChange in the editor. getMaxAggregateTemperatureChange has the following parameter:

  • int tempChange[n]: the temperature change data of n days Returns long: the maximum aggregate temperature change

Constraints

  • 1 ≤ n ≤ 10⁵
  • -10⁹ ≤ tempChange[i] ≤ 10⁹ where, 1 ≤ i ≤ n

Example 1

Input:

tempChange = [6, -2, 5]

Output:

9

Explanation: The aggregate temperature change on each day is evaluated as: For day 1, there are no preceding days info, but the day itself is included in the calculation. Temperature changes = [6] for the before period. For succeeding days, there are values [6, -2, 5] and 6 + (-2) + 5 = 9. Again, the chagne for day 1 is included. The maximum of 6 and 9 is 9. For day 2, consider [6, -2] -> 6 + (-2) = 4, and [-2, 5] -> (-2) + 5 = 3. The maximum of 3 and 4 is 4. For day 3,consider [6, -2, 5] -> 6 + (-2) + 5 = 9, and [5]. The maximum of 9 and 5 is 9. The max aggregate temp change is max (9, 4, 9) = 9.

Example 2

Input:

tempChange = [-1, 2, 3]

Output:

5

Explanation: Explanation hasn't been found yet. If you happen to know about it, feel free to lmk! Manyyy thanks in advance!

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

Amazon Music is working on harmonizing their music playlist. In their playlist system, each song is represented by a binary string music, where '0' and '1' denote two different types of music, say TypeA and TypeB. An "alternating music string" is one where no two adjacent songs are of the same type. For example, "1", "0", "10", "01", "101" are alternating music strings. Given a binary string music representing the playlist and an integer k, you can perform up to k operations where each operation involves flipping a character, i.e., turning '0' into '1' and '1' into '0'. As a developer at Amazon, the task is to determine the longest alternating substring that can be created from the music string by performing at most k operations. Note:

  • A binary string is a sequence of '0' and '1' characters.
  • A string A is a substring of a string B if A can be obtained from B by deleting several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. Function Description Complete the function getMaxAlternatingMusic in the editor. getMaxAlternatingMusic has the following parameters:
  • string music: a string of characters 0 and 1.
  • int k: the number of operations allowed. Returns int: the length of the longest alternating music string that can be created.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Amazon operates a network of n machines. Some are currently inactive, while others are active. The engineers managing the infrastructure have access to a specific procedure that allows toggling the states of machines. In one use of this operation, they can select a continuous segment of machines and invert their statuses—turning active to inactive, and inactive to active. Due to certain restrictions, this procedure can be used at most k times. You are given a binary string machine_status, of length n, where '1' indicates an active machine and '0' represents an inactive one, along with an integer max_flips that denotes the maximum number of operations allowed. Determine the highest possible number of adjacent active machines that can be achieved after at most max_flips operations. Function Description Complete the function getMaxConsecutiveON in the editor. getMaxConsecutiveON has the following parameters:

  • String machine_status: states of the servers, '1' represents ON state, '0' represents OFF
  • int max_flips: the maximum number of operations that can be performed Returns int: The greatest number of back-to-back active machines achievable using no more than max_flips operations

Constraints

  • 1 ≤ n ≤ 2 * 10⁵
  • 1 ≤ max_flips ≤ 2 * 10⁵
  • machine_status contains only 0s and 1s

Example 1

Input:

machine_status = "00010"
max_flips = 1

Output:

4

Explanation: The optimal approach is to perform one flip on the range of indices [0..2]. After flipping: "11110" This results in a sequence of 4 consecutive active machines.

Example 2

Input:

machine_status = "1001"
max_flips = 2

Output:

4

Explanation: You can flip indices [1..2] to obtain "1111". Only one operation is needed to achieve a maximum of 4 continuous active machines. There’s no advantage in using the second operation.

Example 3

Input:

machine_status = "11101010110011"
max_flips = 2

Output:

8

Explanation: Flip indices [7..9]: "11101011000011" Then flip [8..11]: "11101011111111" This strategy yields a block of 8 active machines in a row.

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

It is the third anniversary of Amazon Prime Day, and they have come up with amazing offers yet again! Customers who purchase a pair of products whose prices sum to a power of three receive a 50% discount. Given the prices of n products, find the number of pairs (i, j) such that i Function Description Complete the function getMaxDiscountPairsin the editor below.getMaxDiscountPairs` has the following parameters:

  • int price[n]: the product prices Returns int: the number of pairs whose sum is a power of three.

Example 1

Input:

price = [2, 1, 8]

Output:

2

Explanation: The following pairs will qualify for the discount (0, 1) since 2 + 1 = 3 and (1, 2) since 1 + 8 = 9 = 3². Return 2.

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

IMDB, an Amazon-owned company, is a widely used platform for discovering scores of films and television series. Researchers are examining audience preferences by studying sequences of film scores. One specific metric they focus on is counting how many positions exist where a score is directly followed by a higher score. Their goal is to determine the largest possible count of such positions by rearranging the scores in the most efficient manner. Given an array scores consisting of n integers, compute the highest possible number of indices i such that scores[i] < scores[i + 1] after optimally reordering the array.

Constraints

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

Example 1

Input:

scores = [2, 1, 3]

Output:

2

Explanation:

Example 2

Input:

scores = [2, 1, 1, 2]

Output:

2

Explanation: In this scenairo, an optimal arrangement of the arr scores is [1, 2, 1, 2]. The indices i such that scores[i] < scores[i + 1], are [0, 1]. So answer is 2. P.S. This test cases was added on 04-13-2025 :) Relevant ss was attached in the Problem Source section.

Example 3

Input:

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

Output:

4

Explanation: In this case, an very optimal arrangement of the arr scores is [1, 2, 3, 4, 5]. the indices i such that scores[i] < scores[i + 1], are [0, 1, 2, 3]. So answer is 4. P.S. This test cases was added on 04-13-2025 :) Relevant ss was attached in the Problem Source section.

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

Data analysts at Amazon are analyzing a data set of n strings in the array dataSet[], each consisting of lowercase English letters. Each character in a string corresponds to a particular feature. The information gain obtained by training a model with two strings, dataSet[i] and dataSet[j], is the difference between the lengths of the strings i.e., |len(dataSet[i]) - len(dataSet[j])|. To avoid too many overlapping features, two strings can be selected only if the number of common features between them does not exceed a given threshold, max_common_features. The number of common features here is equal to the number of common characters between the two strings. For example, "abc" and "bcd" have 2 common features 'b' and 'c'. While "aa" and "aaa" have two common features, the "a" two 'a' characters. Given dataSet and max_common_features, determine the maximum information gain possible. Function Description Complete the function getMaxInformationGain in the editor. getMaxInformationGain takes the following arguments:

  • String[] dataSet: the strings of features
  • int max_common_features: the maximum number of common features allowed between data points Returns int: the maximum possible information gain 𓇼 ⋆.˚ 𓆝 𓆡⋆.˚ 𓇼Forever thankful chizzy_elect

Constraints

  • 2 ≤ n ≤ 1000
  • 1 ≤ len(dataSet[i]) ≤ 1000
  • 1 ≤ max_common_features ≤ 1000
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

An AWS client wants to deploy multiple applications and needs two servers, one for their frontend and another for their backend. They have a list of integers representing the quality of servers in terms of availability. The client's preference is that the availability of an application's frontend server must be greater than that of its backend. Two arrays of same size n, frontend[n] and backend[n] where elements represent the quality of the servers, create pairs of elements (frontend[i], backend[i]) such that frontend[i] > backend[i] in each pair. Each element from an array can be picked only once to form a pair, Find the maximum number pairs that can be formed. Function Description Complete the function getMaxPairs in the editor. getMaxPairs has the following parameters:

  • int frontend[n]: frontend server qualities
  • int backend[n]: backend server qualities Returns int: the maximum number of pairs that can be formed

Constraints

N/A

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

Within an Amazon software management tool, there's a collection of software programs and time slots. Each time slot lasts k seconds, and within that time the slots do not overlap. The software programs are required to sequentially from 1 to n, and cannot be interrupted. Each program has a specific execution time denoted as time[i]. The objective is to execute the software programs following a specific algorithm: Start with the first time slot. Proceed sequentially through the software programs from left to right. Execute a program if it can be completed within the current time slot (i.e., the remaining time in the time slot is greater than or equal to the execution time of the program). If a program cannot be completed in the current time slot, move it to the next available time slot (if one is available). Continue this process until the available time slot. If there are no available time slots and some software programs remain to be executed, then the goal is to determine the maximum number of software programs that can be executed using this algorithm. The goal is to determine the maximum number of software programs that can be executed using this algorithm. This can be done by moving to the last program executed within the set of software programs and removing the software programs from the leftmost of the list until the remaining set of software programs can be executed with the available time slots. Find the maximum number of software programs from the suffix that can be executed efficiently using this algorithm. In other words, you are looking for the longest sequence of consecutive software programs from the end of the list that can be successfully scheduled within the given time slots when scheduled according to the rules provided. Function Description Complete the function getMaxPrograms in the editor. getMaxPrograms has the following parameters:

  • int time[n]: an array of integers denoting the execution time of software programs.
  • int m: number of time slots available
  • int k: time length of each time slot Returns int: the maximum number of software programs from the suffix that can be executed. ଓ༉ Many thanks, HxyJxy, Nachos and spike!

Constraints

  • 1 ≤ n, m ≤ 2*10⁵
  • 1 ≤ k ≤ 10⁹
  • `1

Example 1

Input:

time = [5, 2, 1, 4, 2]
m = 2
k = 6

Output:

4

Explanation: Firstly, you try to execute all the 5 software programs.

  • 1st software program will be executed in the first time slot.
  • Since only 1 minute is remaining in the first time slot, 2nd software program will be executed in the second time slot.
  • Now 4 minutes remain in this time slot, so the 3rd software program will be executed in this time slot.
  • Now 3 minutes are remaining in this time slot, but the next software program requires 4 minutes which requires another time slot that is not available. So this set of programs starting from the first program can not be executed. Now you remove the first software program and try to execute the remaining 4 software programs i.e. [2, 1, 4, 2]
  • 1st software program will be executed in the first time slot.
  • Now 4 minutes are remaining in the first time slot, so the 2nd software program will be executed in this time slot.
  • Now 3 minutes are remaining in the first time slot, but the next software program requires 4 minutes which requires another time slot.
  • So, 3rd software program will be executed in the second time slot.
  • Now, 2 minutes are remaining in this time slot in which the last program will get executed. So, all the software programs are executed in this set, hence, the answer is 4.

Example 2

Input:

time = [4, 2, 3, 4, 1]
m = 1
k = 4

Output:

1

Explanation: Since there is only one time slot, of length 4, we can not start from the 1st, 2nd, 3rd, or 4th software program. Only the last software program will be executed. Hence the answer is 1.

Example 3

Input:

time = [1, 2, 3, 1, 1]
m = 3
k = 3

Output:

5

Explanation: All the software programs will be executed in the following manner:

  • 1st and 2nd software programs in the first time slot.
  • 3rd software program in the second time slot.
  • 4th and 5th software programs in the third time slot. Hence the answer is 5.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

HackerLand Sports Club wants to send a team for a relay race. There are n racers in the group indexed from 0 to n - 1. The ith racer has a speed of speed[i] units. The coach decided to send some contiguous subsegments of racers for the race i.e. racers with index i, i + 1, i + 2 ..., j such that each racer has the same speed in the group to ensure smooth baton transfer. To achieve the goal, the coach decided to remove some racers from the group such that the number of racers with the same speed in some contiguous segment is maximum. Given the array, racers, and an integer k, find the maximum possible number of racers in some contiguous segment of racers with the same speed after at most k racers are removed. Function Description Complete the function getMaxRacers in the editor. getMaxRacers has the following parameter(s):

  • int speed[n]: the speeds of the racers
  • int k: the maximum number of racers that can be removed Returns int: the maximum number of racers that can be sent after removing at most k racers

Constraints

  • 1 ≤ n ≤ 3 * 10⁵
  • 1 ≤ k ≤ n

Example 1

Input:

speed = [1, 4, 4, 2, 2, 4]
k = 2

Output:

3

Explanation: It is optimal to remove the two racers with speed 2 to get the racers [1, 4, 4, 4]. Each racer with speed 4 can now be sent as they are in a contiguous segment. A maximum of 3 racers can be sent for the relay race.

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

A manager at Amazon is managing a team of n employees with IDs numbered from 0 to n - 1. Some employees are marketing experts and others are developers. The employee with id i has a skill level of skill[i]. The employee is a marketing expert if expertise[i] is 0 and a developer if expertise[i] is 1. The manager wants to select a team to work on a project with some contiguous set of ids [i, i + 1, i + 2, ..., j] such that there is an equal number of marketing experts and developers and the total sum of skills is maximized. Given two arrays, skill and expertise, find the maximum possible sum of skills of any team that can be formed respecting the above conditions. Note: It is always possible to form a team consisting of zero employees with a total skill of zero. A contiguous set of elements is a sequence where each element is adjacent to the next, with no gaps between them. Each element in the set is directly next to the previous one. Function Description Complete the function getMaxSkillSum in the editor. getMaxSkillSum takes the following arguments:

  • int expertise[n]: the expertise of the employees
  • int skill[n]: the skill level of the employees Returns long: the maximum possible sum of skill levels of the team
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

AWS provides a range of servers to meet the deployment needs of its clients. A client wants to choose a set of servers to deploy their application. Each server is associated with an availability factor and a reliability factor. The client defines the stability of a set of servers as the minimum availability amongst the servers multiplied by the sum of reliabilities of all the servers. Given two arrays of integers, availability, and reliability, where the availability[i] and reliability[i] represent the availability and reliability factors of the ith server, find the maximum possible stability of any subset of servers. Since the answer can be large, report the answer modulo (10⁹ + 7). Function Description Complete the function getMaxStability in the editor below. getMaxStability has the following parameters:

  • int reliability[n]: server reliability values
  • int availability[n]: server availability values Returns int: the maximum stability above among all possible non-empty subsets, modulo (10⁹+7)

Constraints

  • 1 < n ≤ 10⁵
  • 1 ≤ reliability[i], availability[i] ≤ 10⁶
  • It is guaranteed that lengths of reliability and availability are the same.

Example 1

Input:

reliability = [1, 2, 2]
availability = [1, 1, 3]

Output:

6

Explanation: Consider the set of servers where reliability = [1, 2, 2] and availability = [1, 1, 3]. The possible subsets of servers are:

  • Indices {0}: Stability = 1*1 = 1
  • Indices {1}: Stability = 1*2 = 2
  • Indices {2}: Stability = 3*2 = 6
  • Indices {0, 1}: Stability = min(1, 1) * (1+ 2) = 3
  • Indices {0, 2}: Stability = min(1, 3) * (1+ 2) = 3
  • Indices {1, 2}: Stability = min(1, 3) * (2+2) = 4
  • Indices {0, 1, 2}: Stability = min(1, 1, 3) * (1+2+2) = 5 So the answer is the maximum stability for the set of index {2}, answer = 6 % 1000000007 = 6.

Example 2

Input:

reliability = [75, 104, 72, 72, 8, 125]
availability = [1, 2, 2, 1, 2, 1]

Output:

5

Explanation: Take servers at positions 1, 2, 4, and 6. This will cost 5 and the sum of efficiency values is 376. (This new test case was added on 03-31-2025)

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

At a high-paced analytics platform, efficiently scheduling tasks within designated time constraints is crucial. The system consists of n mandatory tasks and n optional tasks. Two arrays, mandatoryTasks and optionalTasks, specify the duration in hours of each task. Here, mandatoryTasks[i] indicates the time required for the i-th mandatory task, while optionalTasks[i] represents the duration of the i-th optional task. Each workday has a strict limit of maxDailyHours, within which tasks must be scheduled. It is required that exactly one mandatory task is scheduled each day. If time permits, at most one optional task can also be included on the same day. The total time spent on a day cannot exceed maxDailyHours. The challenge is to determine the highest number of optional tasks that can be scheduled over the course of n days while adhering to these constraints. Function Description Complete the function computeMaxScheduledTasks in the editor below. computeMaxScheduledTasks has the following parameters:

    1. int maxDailyHours: the maximum number of hours available each day.
    1. int mandatoryTasks[n]: an array representing the duration of mandatory tasks.
    1. int optionalTasks[n]: an array representing the duration of optional tasks. Returns int: the highest number of optional tasks that can be completed within the given constraints.

Constraints

  • 1 ≤ n, maxDailyHours ≤ 2*10⁵
  • 1 ≤ mandatoryTasks[i], optionalTasks[i] ≤ maxDailyHours

Example 1

Input:

maxDailyHours = 7
mandatoryTasks = [4, 5, 2, 4]
optionalTasks = [5, 6, 3, 4]

Output:

2

Explanation: Day 1: Schedule the first mandatory task (4 hours) and the third optional task (3 hours). Total: 4 + 3 = 7 hours. Day 2: Schedule the second mandatory task (5 hours). No optional task can be added. Total: 5 hours. Day 3: Schedule the third mandatory task (2 hours) and the first optional task (5 hours). Total: 2 + 5 = 7 hours. Day 4: Schedule the fourth mandatory task (4 hours). No optional task can be added. Total: 4 hours. After optimizing task scheduling, the maximum number of optional tasks that can be included is 2.

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

The developers at Amazon are working on optimizing their database query times. There are n host servers, where the throughput of the ith host server is given by host_throughput[i]. These host servers are grouped into clusters of size three. The throughput of a cluster, denoted as cluster_throughput, is defined as the median of the host_throughput values of the three servers in the cluster. Each server can be part of at most one cluster, and some servers may remain unused. The total system throughput, called system_throughput, is the sum of the throughputs of all the clusters formed. The task is to find the maximum possible system_throughput. Note: The median of a cluster of three host servers is the throughput of the 2nd server when the three throughputs are sorted in either ascending or descending order. Function Description Complete the function getMaxThroughput in the editor. getMaxThroughput has the following parameter:

  • int host_throughput[n]: an array denoting the throughput of the host servers Returns long: the maximum system_throughput 𓂃 𓈒𓏸 Couldn’t do this without da best spike!𓂃

Constraints

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

Example 1

Input:

host_throughput = [4, 6, 3, 5, 4, 5]

Output:

9

Explanation: Here, n = 6, and the host throughput is given by host_throughput = [4, 6, 3, 5, 4, 5]. The maximum number of clusters that can be formed is 2. One possible way to form the clusters is to select the 1st, 2nd, and 3rd host servers for the first cluster, and the 4th, 5th, and 6th host servers for the second cluster. The cluster_throughput of the first cluster [4, 6, 3] will be 4 (the median), and the cluster_throughput of the second cluster [5, 4, 5] will be 5 (the median). Thus, the system_throughput will be 4 + 5 = 9.

Example 2

Input:

host_throughput = [2, 3, 4, 3, 4]

Output:

4

Explanation: The max number of clusters that can be formed is 1, and two host servers will remain unused. One possible cluster is to select the 1^st, 3^rd, and 5^th host servers. The cluster_throughput of [2, 4, 4] will be 4 (the median value :) Thus, the system_throughput for all clusters will be 4.

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

Amazon games have introduced a new mathematical game for kids. You will be given n sticks and the player is required to form rectangles from those sticks. Formally, given an array of n integers representing the lengths of the sticks, you are required to create rectangles using those sticks. Note that a particular stick can be used in at most one rectangle and in order to create a rectangle we must have exactly two pairs of sticks with the same lengths. For example, you can create a rectangle using sticks of lengths [2, 2, 5, 5] and [4, 4, 4, 4] but not with [3, 3, 5, 8]. The goal of the game is to maximize the total sum of areas of all the rectangles formed. In order to make the game more interesting, we are allowed to reduce any integer by at most 1. Given the array sideLengths, representing the length of the sticks, find the maximum sum of areas of rectangles that can be formed such that each element of the array can be used as length or breadth of at most one rectangle and you are allowed to decrease any integer by at most 1. Since this number can be quite large, return the answer modulo 10⁹+7. Note: It is not a requirement that all side lengths be used. Also, a modulo b here represents the remainder obtained when an integer a is divided by an integer b. Function Description Complete the function getMaxTotalArea in the editor. getMaxTotalArea has the following parameter(s):

  • int sideLengths[n]: the side lengths that can be used to form rectangles Returns int: the maximum total area of the rectangles that can be formed, modulo (10⁹+7).

Constraints

  • 1 ≤ n ≤ 10⁵
  • 2 ≤ sideLengths[i] ≤ 10⁴ where 0 ≤ i < n

Example 1

Input:

sideLengths = [2, 6, 2, 6, 3, 5]

Output:

12

Explanation: The lengths 2, 2, 6, and 6 can be used to form a rectangle of area 2*6=12. No other rectangles can be formed with the remaining lengths. The answer is 12 modulo (10⁹+7)=12.

Example 2

Input:

sideLengths = [2, 3, 3, 4, 6, 8, 8, 6]

Output:

54

Explanation: Two rectangles can be formed. One has sides of 6 and 8, and the other by reducing 4 and one of the 3s by 1 has sides of 2 and 3. The total area of these rectangles is (6*8+2*3) mod (10⁹+7) = 54.

Example 3

Input:

sideLengths = [3, 4, 5, 5, 6]

Output:

20

Explanation: The rectangle can have either sides of 5 and 3 (reduce 4 by 1), or sides of 5 and 4 (reduce 6 and one 5 by 1). The second option has a greater area, so 5*4 > 3*5.

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

Amazon has launched a "Play to Win" game where users get a chance to earn free gift vouchers. The game presents you with an array of integers (arr) and an integer k. You are allowed to choose any contiguous subarray within arr and add an integer x of your choice to all the elements within that subarray. You can do this at most once. The goal is to maximize the number of elements in the entire array that have a value equal to k after performing this operation (choosing a subarray and adding x to it). You need to complete the function getMaximumCount which takes the integer array arr and the target value k as input, and returns the maximum number of elements equal to k that can be achieved. Function Description Complete the function getMaximumCount in the editor. getMaximumCount has the following parameters:

    1. int[] arr: an array of integers
    1. int k: the target value Returns int: the maximum number of elements equal to k that can be achieved

Constraints

  • 1≤n≤2 · 10⁵ (where n is the size of the array arr)
  • 1≤arr[i]≤2 · 10⁵ (for each element in arr)
  • 1≤k≤2 · 10⁵

Example 1

Input:

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

Output:

4

Explanation: If we choose the subarray [4, 3] (from index 3 to 4) and add x = -2 to it, the array becomes [2, 3, 2, 2, 1, 2]. In this new array, there are four elements with the value 2. It's stated that this is the maximal count achievable, so the answer would be 4.

Example 2

Input:

arr = [6, 4, 4, 6, 4, 4]
k = 6

Output:

5

Explanation: By choosing the subarray from index 1 to 5 (inclusive, assuming 0-based indexing, so the subarray is [4,4,6,4,4]) and adding x=2 to it, the subarray becomes [6,6,8,6,6]. The resulting array would be [6,6,6,8,6,6]. This gives us 5 elements equal to k=6, which is stated to be maximal.

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

You are given an array payload of size n, where payload[i] represents the size of the (i)-th event payload. The task is to select a subset of events and rearrange them into a new array optimizedPayload that satisfies the following conditions: The first segment is strictly increasing. The second segment is strictly decreasing. The third segment is strictly increasing. The goal is to maximize the number of events included in optimizedPayload. Function Specification: Complete the function getMaximumEvents in the editor. getMaximumEvents has the following parameter:

  • int payload[n]: Array of payload sizes. Output: int: Maximum number of events that can be selected.

Constraints

  • 2 ≤ n ≤ 2×10⁵
  • 1 ≤ payload[i] ≤ 10⁹
  • payload contains at least 2 distinct elements.

Example 1

Input:

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

Output:

9

Explanation: The subset optimizedPayload = [1, 3, 5, 4, 2, 6, 7, 8, 9] satisfies the increasing-decreasing-increasing sequence configuration.

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

Amazon Fresh is a grocery store designed from the ground up to offer a seamless grocery shopping experience to consumers. As part of a stock clearance exercise at the store, given the number of fresh products, follow the rules given below to stack the products in an orderly manner. There are a total of n piles of products. The number of products in each pile is represented by the array numProducts. Select any subarray from the array numProducts and pick up products from that subarray The number of products you pick from the i-th pile is strictly less than the number of products you pick from the (i+1)th pile for all indices i of the subarray. Find the maximum number of products that can be picked. Function Description Complete the function getMaximum in the editor. getMaximum has the following parameters:

  • int numProducts[n]: the number of products in each pile. Returns int: the maximum number of products that can be picked Much obliged, spike!!

Constraints

  • 1 ≤ n ≤ 5000
  • 1 ≤ numProducts[i] ≤ 10⁹

Example 1

Input:

numProducts = [7, 4, 5, 2, 6, 5]

Output:

12

Explanation: These are some ways strictly increasing subarrays can be chosen (1-based index): • Choose subarray from indices (1, 3) and pick products (3, 4, 5) respectively from each index, which is 12 products. Note that we are forced to pick only 3 products from index 1 as the maximum number of products we can pick from index 2 is 4, and we need to make sure that it is greater than the number of products picked from index 1. • Choose subarray from indices (3, 6) and pick products (1, 2, 4, 5) respectively from each index, which is 12 products. Similar to the above case, we are forced to pick only 1 product from index 3 as the maximum number of products at index 4 is only 2. • Choose subarray from indices (3, 5) and pick products [1, 2, 6] respectively from each index, which is 9 products.

  • Choose subarray from indices (1, 1) and pick all the 7 products. The max num of products is 12 :)

Example 2

Input:

numProducts = [2, 9, 4, 7, 5, 2]

Output:

16

Explanation: A few examples of how you can pick the products (1-based index): • Choose subarray from indices (1, 2) and pick products (2, 9) respectively from each index, which is 11 products. • Choose subarray from indices (1, 4) and pick products (2, 3, 4, 7), which is 16 products. • Choose subarray from indices (1, 5) and pick products (1, 2, 3, 4, 5), which is 15 products.

Example 3

Input:

numProducts = [2, 5, 6, 7]

Output:

20

Explanation: Take all the products as they already are in incresing order. (p.s. the source image is super blurry, I kinda think output is 20)

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

Given an array videoScores, of length n, representing the current relevance scores of videos in the recommendation system (i.e., how much a video matches the user's interests, with higher values indicating better matches), the task is to adjust the scores to make all the videos no longer recommended (i.e., reduce all the scores to 0 or below). Each adjustment decreases one of the video scores by a fixed integer value x. The task is to find the minimum value of x such that after performing at most maxAdjustments adjustments, all the relevance scores will become non-positive (i.e., less than or equal to zero). Function Description Complete the function getMinAdjustments in the editor below. getMinAdjustments takes the following parameter:

  • int videoScores[n]: the current relevance scores of videos in the recommendation system
  • int maxAdjustments: the maximum number of adjustments allowed Returns int: the minimum possible integer x required

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ videoScores[i] ≤ 10⁹
  • n ≤ maxAdjustments ≤ 10⁹

Example 1

Input:

videoScores = [4, 3, 2, 7]
maxAdjustments = 5

Output:

2

Explanation: If x = 1, elements can be decreased by 1 in an operation and it would take a total of 6 adjustments to make all the elements non-positive which exceeds the maxAdjustments allowed. If the chosen x = 2, then:

  • In the first operation, we decrease the first element. The array becomes [-1, 2, 3]
  • In the second operation, we decrease the second element. The array becomes [-1, 0, 3]
  • In the third operation, we decrease the third element. The array becomes [-1, 0, 1]
  • In the fourth operation, we decrease the third element again. The array becomes [-1, 0, -1] Hence, x = 2 is the minimum possible integer respecting the given conditions. Thus, the answer is 2.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Amazon Kindle has several e-books that customers can purchase directly. There are n books ordered sequentially numbered 1, 2,.., n, where the i^th book has a cost of cost[i]. A customer wants to purchase all the books, and kindle offers the customer a unique scheme is described as the follows - Let the leftmost book remaining in the sequence be book i. The customer can choose to buy the leftmost book individually for cost[i]. This book is then removed from the sequence. Let the rightmost book remaining in the sequence be book j. The customer can choose to buy the rightmost book individually for cost[j]. This book is then removed from the sequence. The customer can also choose to pay the amount pariCost for both the leftmost and rightmost books together. In this case, both the leftmost and rightMostbooks are removed. This option can be used as many as k times. Given the cost of books cost, the cost to purchase the leftmost and rightmost books together, parCost, and the mx num of times the pairCost option can be applied k, find the min cost in which the customer can purchase all the books following the scheme above. Function Description Complete the function getMinCost in the editor. getMinCost has the following parameters:

  • int cost[n]: the cost of each book
  • int pairCost: the cost of purchase the leftmost and rightmost book together
  • int k: the MAX NUM of times pairCost can be used Returns long int: the min cost to purchase all books

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ pairCost ≤ 10⁹
  • 1 ≤ k ≤ n
  • 1 ≤ cost[i] ≤ 10⁹
  • The cost array may not be in increasing order

Example 1

Input:

cost = [1, 2, 3]
pairCost = 2
k = 1

Output:

3

Explanation: The min cost to purchase the books is 1 + 2 = 3. the ans is 3.

Example 2

Input:

cost = [1, 1, 1]
pairCost = 2
k = 1

Output:

3

Explanation: Purchase the books individually for 1 + 1 + 1 = 3. This new example test case was added on 07-03-2025. You can find relevant source image in the Problem Srouce section.

Example 3

Input:

cost = [9, 11, 13, 15, 17]
pairCost = 6
k = 2

Output:

21

Explanation: Purchase the leftmost book. cost[0] = 9. Purchase the leftmost and rightmost for pairCost = 6. Purchase the leftmost and rightmost books for pairCost = 6. The total cost is 9 + 6 + 6 = 21. This new example test case was added on 07-03-2025. You can find relevant source image in the Problem Srouce section.

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

Amazon's database doesn’t support very large numbers, so numbers are stored as a string of binary characters, '0' and '1'. Accidentally, a '!' was entered at some positions and it is unknown whether they should be '0' or '1'. The string of incorrect data is made up of the characters '0', '1' and '!' where '!' is the character that got entered incorrectly. '!' can be replaced with either '0' or '1'. Due to some internal faults, some errors are generated every time '0' and '1' occur together as '01' or '10' in any subsequence of the string. It is observed that the number of errors a subsequence '01' generates is x, while a subsequence '10' generates y errors. Determine the minimum total errors generated. Since the answer can be very large, return it modulo 10⁹+7. Note: A subsequence of a string is obtained by omitting zero or more characters from the original string without changing their order. Hint: It can be proved that (a + b) % c = ((a% c) + (b % c)) % c where a, b, and c are integers and % represents the modulo operation. Function Description Complete the function getMinErrors in the editor. getMinErrors has the following parameter(s):

  • String errorString: a string of characters '0', '1', and '!'
  • int x: the number of errors generated for every occurrence of subsequence 01
  • int y: the number of errors generated for every occurrence of subsequence 10 Returns int: the minimum number of errors possible, modulo 10⁹+7 spike ໒꒱˚ deserves all the applause!

Constraints

  • 1≤ len (errorString)≤10⁵
  • 0 ≤ x, y ≤ 10⁵
  • s consists only of characters '0', '1', and 'l'

Example 1

Input:

errorString = "101!1"
x = 2
y = 3

Output:

9

Explanation: If the '!' at index 3 is replaced with '0', the string is "10101". The number of times the subsequence 01 occurs is 3 at indices (1, 2), (1, 4), and (3, 4). The number of times the subsequence 10 occurs is also 3, indices (0, 1), (0, 3) and (2, 3). The number of errors is 3 * x + 3 * y = 6 + 9 = 15. If the '!' is replaced with '1', the string is "10111". The subsequence 01 occurs 3 times and 10 occurs 1 time. The number of errors is 3 * x + y = 9. The minimum number of errors is min(9, 15) modulo (10⁹ + 7) = 9.

Example 2

Input:

errorString = "01!0"
x = 2
y = 2

Output:

6

Explanation: The better string is 0100 with one substring 01 at index (0,1) and two subsequence of 10 at indices (1,2) and (2,3) making total errors generate = 2 * 1 + 2 * 2 = 6.

Example 3

Input:

errorString = "!!!!!!!"
x = 23
y = 27

Output:

0

Explanation: There is a tie for the best string generated, 00000 or 11111, with zero substrings 01 or 10.

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

Developers at Amazon are working on a new algorithm using the Bitwise XOR operation. Given an array arr of even length n, Developers can perform an operation on a given array which is defined below as many times as necessary: Choose two indices L and R, where 0 ≤ L ≤ R Let xbe the bitwise XOR of all elements of the subarray represented by indicesLandRof the given array. Assign all elements of the chosen subarray tox. Given an integer array arr[], find the minimum number of elements of the required to make all operations given array equal to zero. Note: Bitwise XOR for an array of numbers is determined by counting each bit position across all numbers in the array. If the total count of set bits at a bit-position is odd, the resulting bit in output is set to 1. Otherwise, the resulting bit is set to 0.. **Function Description** Complete the function getMinMovesin the editor below.getMinMoves` has the following parameter(s):

  • int arr[n]: the array Returns int: the minimum number of moves to make all elements of the array equal to zero

Constraints

  • n is supposed to be even
  • 0 ≤ arr[i] < 2²⁰
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Imagine you are shopping on Amazon.com for some good weight lifting equipment. The equipment you want has blocks of many different weights that you can combine to lift. The listing on Amazon gives you an array, blocks, that consists of n different weighted blocks, in kilograms. There are no two blocks with the same weight. The element blocks[i] denotes the weight of the ith block from the top of the stack. You consider weight lifting equipment to be good if the block at the top is the lightest, and the block at the bottom is the heaviest. More formally, the equipment with array blocks will be called good weight lifting equipment if it satisfies the following conditions assuming the index of the array starts from 1: blocks[1] Function Description Complete the function getMinNumMoves in the editor. getMinNumMoves has the following parameter:

  • int blocks[n]: the distinct weights Returns int: the minimum number of operations required

Constraints

  • 2 ≤ n ≤ 10⁵
  • 1 ≤ blocks[i] ≤ 10⁹ for all 1 ≤ i ≤ n
  • blocks consists of distinct integers.

Example 1

Input:

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

Output:

3

Explanation: The lightest block needs to move left. The heaviest block is already in the correct position.

  • In the first move, swap the third and the fourth blocks: blocks = [2, 4, 1, 3, 6].
  • Swap the second and the third blocks: blocks = [2, 1, 4, 3, 6].
  • Swap the first and the second blocks: blocks = [1, 2, 4, 3, 6].

Example 2

Input:

blocks = [4, 11, 9, 10, 12]

Output:

0

Explanation: The blocks are already in their correct positions.

Example 3

Input:

blocks = [3, 2, 1]

Output:

3

Explanation: Let the blocks be in the order: blocks = [3, 2, 1] In the first move, we swap the first and the second blocks. After swapping, the order becomes: blocks = [2, 3, 1] In the second move, we swap the second and the third blocks. After swapping, the order becomes: blocks = [2, 1, 3] In the third move, we swap the first and second blocks. After swapping, the order becomes: blocks = [1, 2, 3] Now, the array satisfies the condition after 3 moves.

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

The management team at one of Amazon's warehouse facilities is planning to install a smart lighting system. A total of n smart bulbs will be installed along a straight line. A smart bulb automatically turns OFF if the sum of the brightness of the bulbs in front of it is greater than its own brightness. The bulbs can be rearranged in any order. The team wants to find out the minimum number of bulbs that will turn OFF across all possible permutations of the sequence of bulbs. Given an array, brightness, that represents the brightness of the bulbs placed along a straight line, find the minimum number of bulbs that will turn OFF if the bulbs can be rearranged in any order. Note: All bulbs are turned ON initially. They turn OFF (in order, from left to right) based on the condition mentioned above.

Example 1

Input:

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

Output:

2

Explanation: Suppose, n = 5, brightness = [2, 1, 3, 4, 3] Some of the possible arrangements of bulbs, their final states, and the corresponding number of OFF bulbs are as follows - Arrangement | Final State | OFF Count [2, 1, 3, 4, 3] [T, T, T, F, F] = 3 [2, 3, 4, 1, 3] [T, T, T, F, F] = 3 [3, 2, 4, 1, 3] [T, T, T, F, F] = 3 [4, 3, 3, 2, 1] [T, T, F, F, F] = 4 [1, 2, 3, 4, 3] [T, T, T, T, F] = 2 [3, 3, 1, 4, 2] [T, T, T, F, F] = 3 Note: T = ON state, F = OFF state One of the optimal arrangements is [1, 2, 3, 4, 3]. The minimum number of OFF bulbs in the final state is 2. One of the optimal arrangements is [1, 2, 3, 4, 3]. The minimum number of OFF bulbs in the final state is 2.

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

Make a source array equal to a target array using some given operations. More formally, given an array source of length n, either add 1 to any prefix of the array or add 1 to any suffix of the array. That is, in one operation choose some index i and add 1 to source[0], source[1] ... source[i] or add 1 to source[i], source[i + 1]...source[n - 1]. Find the minimum number of operations required to make the arrays equal. If it is impossible to make the two arrays equal, report -1 as the answer. Function Description Complete the function getMinOperations in the editor below. getMinOperations has the following parameters:

  • int[] source: an array of integers
  • int[] target: an array of integers spike = 100% Awesome𓂃

Example 1

Input:

source = [1, 2, 3, -1, 0]
target = [3, 4, 3, 0, 4]

Output:

6

Explanation: Given n = 5, source = [1,2,3,-1,0], target = [3,4,3,0,4]

  • Choose i = 1 and add 1 to the prefix and perform this operation two times - source = [3,4,3,-1,0], target = [3,4,3,0,4]
  • Choose i = 3 and add 1 to the suffix - source = [3,4,3,0,1], target = [3,4,3,0,4]
  • Choose i = 4 and add 1 to the suffix and perform this operation three times - source = [3,4,3,0,4], target = [3,4,3,0,4] The answer is 2 + 1 + 3 = 6.

Example 2

Input:

source = [1, 2, 2]
target = [2, 2, 3]

Output:

2

Explanation: We can make the two arrays equal in 2 operations -

  1. Choose i = 0 and add 1 to the prefix source = [1, 2, 2] -> [2, 2, 2]
  2. Choose i = 2 and add 1 to the suffix source = [2, 2, 2] -> [2, 2, 3] = target Hence, the answer is 2 and it can be shown that it cannot be less than 2.

Example 3

Input:

source = [1, 2, 2]
target = [2, 2, 3]

Output:

2

Explanation: We can make the two arrays equal in 2 operations -

  1. Choose i = 0 and add 1 to the prefix source = [1, 2, 2] -> [2, 2, 2]
  2. Choose i = 2 and add 1 to the suffix source = [2, 2, 2] -> [2, 2, 3] = target Hence, the answer is 2 and it can be shown that it cannot be less than 2.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

There are n products in an Amazon catalogue, where the category of the i^th product is represented by the array catalogue. The catalogue will be called valid if the number of distinct product categories in it is at most k. If the catalogue is not valid initially, then make it valid by removing some products from the catalogue. Given n products and an array catalogue, find the minimum number of products to remove from the catalogue to make it valid. Function Description Complete the function getminRemoval in the editor below. getminRemoval has the following parameter(s):

  • int catalogue[n]: the category of the products
  • int k: the maximum number of distinct product categories Returns int: the minimum number of elements to remove from catalogue to make it valid.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ k ≤ 10⁵
  • 1 ≤ catalogue[i] ≤ 10⁵

Example 1

Input:

catalogue = [3, 3, 5, 7]
k = 1

Output:

2

Explanation: We can also remove [3, 3, 5] or [3, 3, 7]. However, the number of removed products in these cases is 3, which is not the minimum. Hence, the answer is 2.

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

Some developers at Amazon are building a prototype for a simple rate-limiting algorithm. There are n requests to be processed by the server, represented by a string requests, where the i-th character represents the region of the i-th client. Each request takes 1 unit of time to process. There must be a minimum time gap of minGap units between any two requests from the same region. The requests can be sent in any order, and there can be gaps in transmission for testing purposes. Find the minimum amount of time required to process all the requests such that no request is denied. Function Description Complete the function getMinTime in the editor. getMinTime has the following parameters:

  • n: int: the number of requests
  • requests: String: a string representing the region of each request
  • minGap: int: the minimum time gap required between requests from the same region Returns The function should return an integer representing the minimum time required to process all requests without denial.

Constraints

  • 1 ≤ length of requests ≤ 10⁵
  • 0 ≤ minGap ≤ 100
  • It is guaranteed that requests contain lowercase English characters
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Developers at Amazon have deployed an application with a distributed database. It is stored on total_servers different servers numbered from 1 to total_servers that are connected in a circular fashion, i.e. 1 is connected to 2, 2 is connected to 3, and so on until total_servers connects back to 1. There is a subset of servers represented by an array servers of integers. They need to transfer the data to each other to be synchronized. Data transfer from one server to one it is directly connected to takes 1 unit of time. Starting from any server, find the minimum amount of time to transfer the data to all the other servers. Function Description Complete the function getMinTime in the editor. getMinTime takes the following arguments:

  • int total_servers: The number of servers in the system
  • int servers[n]: The servers to share the data with Returns int: The minimum time required to transfer the data on all the servers A million thanks, spike

Constraints

  • 1 ≤ total_servers ≤ 10⁹
  • 1 ≤ n ≤ 10⁵
  • 1 ≤ servers[i] ≤ n

Example 1

Input:

total_servers = 8
servers = [2, 6, 8]

Output:

4

Explanation: Two possible paths are shown, but there can be many more. One path goes from 2 to 6 to 8 taking 6 units of time. The other path goes from 2 to 8 to 6 and takes 4 units of time. Return the shorter path length, 4.

Example 2

Input:

total_servers = 5
servers = [1, 5]

Output:

1

Explanation: The two servers are directly connected so it will take only 1 unit of time to share the data.

Example 3

Input:

total_servers = 10
servers = [4, 6, 2, 9]

Output:

7

Explanation: An optimal strategy is to start from server 2 and go to 4, then 6, then 9. It takes 2 + 2 + 3 = 7 units of time.

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

An online retailer offers products in n different dimensions as specified in the array dimensions. The category supervisor notices that several dimensions are redundant and do not offer a favorable customer experience. To optimize the available stock, the product should be offered in unique dimensions. The dimension of the i-th product, dimensions[i], can be augmented by one unit for a fee given in the adjustmentCosts array, adjustmentCosts[i]. Determine the minimal total fee required to ensure that all product dimensions are unique. dimensions === size, cost === adjustmentCosts

Constraints

  • 1 ≤ n ≤ 2 * 10⁵
  • 1 ≤ size[i] ≤ 10⁹
  • 1 ≤ cost[i] ≤ 10⁴

Example 1

Input:

dimensions = [3, 7, 9, 7, 8]
adjustmentCosts = [5, 2, 5, 7, 5]

Output:

6

Explanation: Increase the second value in size from 7 to 10 at a cost of 3 * 2 = 6.

Example 2

Input:

dimensions = [3, 3, 4, 5]
adjustmentCosts = [5, 2, 2, 1]

Output:

5

Explanation: • Increase the second 3 to 5 at a cost of 2 * 2 = 4. • Increase 5 to 6 at a cost of 1. • Total cost = 5.

Example 3

Input:

dimensions = [2, 3, 3, 2]
adjustmentCosts = [2, 4, 5, 1]

Output:

7

Explanation: Process: The array size contains duplicate values. Adjust size[3] from 2 to 3 at a cost of 1 × 1 = 1. Adjust size[2] from 3 to 4 at a cost of 1 × 4 = 4. The total cost is 7. Alternatively, • Adjust size[1] to 5, which costs cost[1] * (5 - size[1]) = 8, and • Adjust size[3] to 4, which costs cost[3] * (4 - size[3]) = 2. • Therefore, the total cost = 8 + 2 = 10. Thus, 7 is the minimum cost required to make all sizes distinct.

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

The supply chain manager at one of Amazon's warehouses is shipping the last container of the day. All n boxes have been loaded into the truck with their sizes represented in the array boxes. The truck may not have enough capacity to store all the boxes though, so some of the boxes may have to be unloaded. The remaining boxes must satisfy the condition max(boxes) ≤ capacity * min(boxes). Given the array, boxes, and capacity, find the minimum number of boxes that need to be unloaded. Function Description Complete the function getMinimumBoxes in the editor. getMinimumBoxes has the following parameters:

    1. int[] boxes: an array of integers representing the sizes of the boxes
    1. int capacity: the capacity of the truck Returns int: the minimum number of boxes that need to be unloaded

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ boxes[i] ≤ 5 * 10⁵
  • above are just partial constraints. I will add more once find reliable sources
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Amazon's software developers are working on enhancing their inventory management system with a new pricing adjustment operation on an array of products, where the price of the i^th product is given by prod_price[i]. The objective is to determine the minimum number of price adjustments needed to ensure that the Amazon price algorithm yields the same price for the sums of all subarrays of length k within the array prod_price. Price adjustment operations can be performed as follows: Modify any number of values in the array prod_price[i] to positive integers. Given the array prod_price and a positive integer k, find the minimum number of changes required so that the sum of elements in all contiguous segments of length k is equal. Note: A subarray is a contiguous segment of an array. Function Description Complete the function getMinimumChanges in the editor. getMinimumChanges has the following parameters:

  • int[] prod_price: an array of integers representing the price of each product
  • int k: an integer representing the length of the subarray Returns int: the minimum number of changes required
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are managing operations at a large Amazon warehouse. Loaded trucks arrive at the warehouse sequentially and must be unloaded within a specific timeframe to ensure timely delivery. Your task is to determine the minimum number of dock bays needed to unload all trucks within the given timeframe. Formally, given a scheduling array truckCargoSize of length n, where each unit in the array represents the amount of time in minutes that a dock bay will take to unload the cargo from the ith truck, and a second integer, maxTurnaroundTime, representing the total allowed time to unload trucks, find the smallest number of dock bays d that will enable you to unload all trucks within maxTurnaroundTime minutes. Notes: As soon as a dock bay becomes available after unloading a truck, it can immediately start processing the next truck. It is guaranteed that unloading all trucks is possible with some number of dock bays. Only the start times of unloading need to be considered in order, not the finish times. Function Description Complete the function getMinimumDockBays in the editor. getMinimumDockBays has the following parameters:

  • int truckCargoSize[n]: the time in minutes for the dock bay to unload cargo from the ith truck
  • long maxTurnaroundTime: the maximum allowed total unloading time. Returns int: the smallest number of dock bays d to unload all the cargo within maxTurnaroundTime minutes.

Constraints

  • 1 ≤ n ≤ 5 * 10⁴
  • 1 ≤ maxTurnaroundTime ≤ 10¹⁵ (looks like 15 to me..)
  • 1 ≤ truckCargoSize[i] ≤ min (maxTurnaroundTime 10⁹)

Example 1

Input:

truckCargoSize = [3, 4, 3, 2, 3]
maxTurnaroundTime = 8

Output:

3

Explanation: Attemping with two dock bays (d = 2): Truck Processing Timeline for 2 Dock1 Bays: With two dock bays, all trucks unloaded in 9 minutes, which exceeds the maxTurnaroundTime of 8 minutes: Attempting with three dock bays (d = 3): With three dock bays, all trucks are unloaded in 6 minutes, which is within the maxTurnaroundTime of 8 minutes. So, the minimum number of dock bays required to unload all trucks within 8 minutes is 3.

Example 2

Input:

truckCargoSize = [2, 3, 1]
maxTurnaroundTime = 7

Output:

1

Explanation: With only one dock bay, all trucks can be unloaded in 2 + 1 = 3 = 6 minutes, which is within the maxTurnaroundTime of 7 minutes.

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

Amazon handles the shipment of millions of packages worldwide daily. At one of their facilities, there are m distinct product categories scheduled for shipment. The count of parcels for product type i is represented by items[i]. Each delivery truck comes with a fixed load limit, defined by capacity, and there’s an additional restriction that no more than max_same_type_limit parcels of any single product type can be loaded onto a truck. Your task is to compute the minimum number of trucks required to transport all the parcels while adhering to both the truck capacity and product-specific constraints.

Example 1

Input:

items = [2, 4]
capacity = 3
max_same_type_limit = 2

Output:

2

Explanation: There are n = 2 product types. The parcel counts are items = [2, 4]. Each truck can carry up to 3 parcels total, but no more than 2 of any specific product type per truck. Our loading Strategy: Truck 1: Load 1 parcel of type 1 and 2 parcels of type 2. Total = 3 (within capacity) Truck 2: Load 1 parcel of type 1 and 2 parcels of type 2. Total = 3 (within capacity) Note: Loading 3 parcels of type 2 into one truck is invalid since max_same_type_limit = 2. Therefore, all parcels are shipped in 2 trucks without breaking any conditions. Final Answer: 2

Example 2

Input:

items = [4, 4, 3]
capacity = 3
max_same_type_limit = 3

Output:

4

Explanation: no source so far..Will update once find it..

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

A well-known consumer brand selling everyday products on Amazon is facing a supply issue due to daily changes in product demand. To manage this, Amazon has set up n distribution hubs, each labeled with a unique number from 1 to n. Amazon decides which hub to use each day by comparing the current day’s demand with the previous day’s: If today’s demand is higher, a hub with a larger number than yesterday’s is chosen. If today’s demand is lower, a hub with a smaller number than yesterday’s is used. If today’s demand is the same, the same hub as yesterday is selected. The total cost for the brand is based on how many different hubs are used over time. Your task is to find the minimum number of unique distribution hubs needed to handle the demand across all n days.

Example 1

Input:

n = 5
dailyTrend = [10, 20, 30, 15, 10]

Output:

3

Explanation: We can assign distribution hubs in the order: [1, 2, 3, 2, 1], which leads to a total cost of 3, since the distinct hubs used are [1, 2, 3]. It’s important to note that other valid sequences of hubs can also satisfy the demand pattern. For instance, the sequence [4, 5, 8, 5, 4] is also valid and involves the unique hubs [4, 5, 8], which again results in a cost of 3. However, no valid arrangement can reduce the cost below 3, as that’s the minimum number of unique distribution hubs needed to match the demand changes across all days. Therefore, the correct answer is 3.

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

You are given an integer list named data. The objective is to adjust all elements in this list so that each becomes zero. You can carry out the following move any number of times: --> Pick a prefix portion of the list and either increase or decrease every element in that prefix by 1. Your task is to figure out the fewest moves required to turn all the elements into zero. Output - Print a single number — the minimum number of steps needed. A prefix segment refers to a continuous collection of elements starting from the first item in the sequence. For instance, [1], [1, 2], [1, 2, 3], and so on are valid prefixes of the sequence [1, 2, 3, 4, 5]. It is assured that turning all values in the list to zero is always achievable.

Constraints

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

Example 1

Input:

d = [3, 2, 1]

Output:

3

Explanation: The most optimal sequence of steps is as follows: Step 1: Choose a prefix of size 2 and reduce each element by 1. After this operation, the list becomes [2, 1, 1]. Step 2: Choose a prefix of size 1 and reduce its value by 1. The list now looks like [1, 1, 1]. Step 3: Select a prefix covering 3 elements and decrease all by 1. After this, the list turns into [0, 0, 0]. The total number of operations required is 3. It is not possible to turn all elements into zero using fewer steps.

Example 2

Input:

d = [3, 2, 0, 0, -1]

Output:

5

Explanation: Step 1: Select a prefix of length 1 and subtract 1 from it. After this step, the list updates to [2, 2, 0, 0, -1]. Step 2: Choose the first 2 elements and decrease them by 1. Now, the list becomes [1, 1, 0, 0, -1]. Step 3: Pick a prefix containing the first 4 elements and reduce each by 1. After performing this, the list changes to [0, 0, -1, -1, -1]. Step 4: Select the first 2 elements and decrease them by 1. The updated list is [-1, -1, -1, -1, -1]. Step 5: Finally, choose the entire list (prefix length 5) and add 1 to every element. The list becomes [0, 0, 0, 0, 0].

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

Amazon Prime Games is designing a game. The player needs to pass n rounds sequentially in this game. Rules of play are as follows: The player loses power[i] health to complete round i. The player's health must be greater than 0 at all times. The player can choose to use armor in any one round. The armor will prevent damage of min(armor, power[i]). Determine the minimum starting health for a player to win the game. Function Description Complete the function getMinimumValue in the editor below. getMinimumValue has the following parameters:

  • int power[n]: the health cost of each round
  • int armor: the maximum amount of health that may be returned one round only Returns int: the minimum amount of health required at the beginning of the game
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

DAs at TomTom Global are deeply engaged in the analysis of the info gained when the company's re-inforcement learning AI model named Supa Helo is trained with different arrangements of exact the same dataset. This time, the process involves exploring how the order of data points tends to affect the model's overall performance. That being said, for an arr of n integers, denoted as data, the analysts all agree that the arrangement is represented using a permutation of the integers from 1 to n. DAs at TomTom Global soon observed that the information gained for a given specific permutation p of the n integers in the arr data can be quantified using a special formula. Detaily speaking, the info gained == sum of i * data[p[i]] for all indices i from 0 to n :) You are required to complete the func pre-defined in the editor on the right side of this page This func has int[] data, which is an arr of integers, as its parameter. If doing right, your implementation should return an int[] that represents the lexicographically smallest permutation p with the maximum info gain. Memo: A permutation p is considered lexicographically smaller than another permutation pp if, at the first index i where p[i] and pp[i] differ, p[i] is less than pp[i]. This concept is crucial when determining the smallest permutation among multiple valid options.

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

Amazon aims to optimally package parcels to improve efficiency. There are n parcels (0-based indexing), and the price of the ith parcel is denoted by prices[i]. Amazon uses five different stamps (indexed from 1 to 5) to label the parcels. Packaging is done sequentially from left to right, and each parcel must be labeled with one of the five stamps. A packaging is considered perfect if it adheres to the following rules (for i > 0): If prices[i] > prices[i-1], then stamp[i] > stamp[i-1] (where stamp[i] is the index of the stamp used to label the ith parcel). If prices[i] If prices[i] = prices[i-1], then stamp[i] ≠ stamp[i-1]. Given an array of nintegers, find the number of perfect packaging possibilities using the five different stamps. Since the number of perfect packaging can be large, return the result modulo (10⁹ + 7). Note: If no valid packaging can be done based on the given rules, return 0. **Function Description** Complete the functiongetNumPerfectPackagingin the editor.getNumPerfectPackaging` has the following parameter:

  • int prices[n]: the price of the parcels Returns int: the number of perfect packaging that can be done modulo (10⁹ + 7)

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ prices[i] ≤ 10⁵

Example 1

Input:

prices = [3, 1, 1]

Output:

40

Explanation: Here, the first parcel can be labeled with any stamp. The index of the stamp used to label the second parcel must be smaller than the one used for the first parcel. Additionally, the stamp used to label the last parcel must not be the same as the one used for the second parcel. i.e. [3, 2, 1], [4, 2, 1], [4, 3, 2], [4, 3, 1], and so on.

Example 2

Input:

prices = [1, 2, 3]

Output:

10

Explanation: There are 10 perfect packaging combinations that can be done by labeling he parcels. For example, [1, 2, 3] means that the first parcel is labeled with the first-indexed stamp, the second parcel with the second-indexed stamp, and the third parcel with the third-indexed stamp. Hence, the ans is 10 :)

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

A product manager at Amazon wants to choose a two-member team for a project. There are n employees to choose from where the i-th employee has a skill, skill[i]. The project needs a total skill between min_skill and max_skill, both inclusive. Given the array skill and two integers min_skill and max_skill, find the number of pairs of employees whose sum of skills is between min_skill and max_skill, both inclusive. Function Description Complete the function getNumTeams in the editor below. getNumTeams takes the following arguments:

  • int skill[n]: the skills of the employees
  • int min_skill: the minimum total skill
  • int max_skill: the maximum total skill Returns long int: the number of pairs of employees with the sum of skills in the given range

Constraints

<l

Example 1

Input:

skill = [2, 3, 4, 5]
min_skill = 5
max_skill = 7

Output:

4

Explanation: Skill 1 | Skill 2 | Skill Sum 2 | 3 | 5 2 | 4 | 6 2 | 5 | 7 3 | 4 | 7 Thus there are 4 possible pairs of employees.

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

Your team at AMZ is currently working on an innovative algorithm to generate password suggestions when users create a brand-new account. Imagine a string composed solely of lowercase English letters that qualifies as "redundancy-free" — meaning that each individual character appears at most once within that string. To ensure minimal repetition, the developers want to suggest a password that can be split into the smallest number of these redundancy-free segments. In this challenge, you are provided with an input string called userPassword. Your task is to determine the minimum number of segments into which userPassword can be partitioned so that every segment is redundancy-free. Function Description Complete the function getNumberRedundancyFree in the editor. getNumberRedundancyFree has the following parameter:

  • string userPassword: the given password Returns int: The minimum number of segments required to divide the string into redundancy-free parts :)

Constraints

  • 1 ≤ length of userPassword ≤ 10⁵
  • All characters in userPassword are lowercase English letters.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

There are n processes. The i-th process has resource[i] number of resources. All the resource[i] are distinct. The CPU wants the processes to be arranged in increasing order of their resource[i]. The CPU does several operations to make this. In each operation, the CPU selects an integer x and a process with number of resources x. It then places all processes with resource values less than x before the processes with resource values greater than or equal to x, maintaining their original order i.e. the relative order between processes having resource value less than x should be maintained and the same applies for processes having resource value greater than or equal to x. Find the lexicographically smallest sequence of Xs that the CPU chooses, such that it takes the minimum number of operations to complete the task. Note: If the minimum number of operations = 0, then return a sequence only containing the integer -1. Function Description Complete the function getOperations in the editor below. getOperations has the following parameter(s):

  • int resource[n]: Contains the number of resources of each process Returns int[]: Lexicographically smallest sequence of Xs such that it takes the minimum number of operations to complete the task.

Constraints

  • 1 ≤ n ≤ 50
  • 1 ≤ resource[i] ≤ 10⁹
  • All resource[i] are distinct

Example 1

Input:

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

Output:

[2, 3, 4, 6]

Explanation: There MIGHT be something wrong in this explanation. I am not quite sure about it. If you found anything wrong, pls feel free to lmk! Many thanks in advance! Happy Coding! CPU can achieve the minimum number of operations in the following way (underlined elements denote the processes that have less than x resources): Choose x=2: [6,4,3,5,2,1] -> [1, 6,4,3,5,2] Choose x=3: [1, 6,4,3,5,2] -> [1, 2, 6,4,3,5] Choose x=4: [1, 2, 6,4,3,5] -> [1, 2, 3, 6,4,5] Choose x=6: [1, 2, 3, 6,4,5] -> [1, 2, 3, 4, 5, 6] Minimum number of operations = 4, and the answer is [2, 3, 4, 6].

Example 2

Input:

resource = [10, 5, 14, 12, 13]

Output:

[14, 15]

Explanation: The optimal way is: Choose x = 14: [15, 10, 14, 12, 13] -> [10, 12, 13, 15, 14] Choose x = 15: [10, 12, 13, 15, 14] -> [10, 12, 13, 14, 15] So, the answer is [14, 15].

Example 3

Input:

resource = [2, 4, 14, 10, 5, 3]

Output:

[4, 10, 14]

Explanation: The optimal way is: Choose x = 4: [2, 4, 14, 10, 5, 3] -> [2, 3, 4, 14, 10, 5] Choose x = 10: [2, 3, 4, 14, 10, 5] -> [2, 3, 4, 5, 14, 10] Choose x = 14: [2, 3, 4, 5, 14, 10] -> [2, 3, 4, 5, 10, 14] So, the answer is [4, 10, 14].

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

Data analysts at Amazon are building a utility to identify redundant words in advertisements. They define a string as redundant if the length of the string, |word| = a * V + b * C, where a and b are given integers and V and C are the numbers of vowels and consonants in the string word. Given a string word, and two integers, a, and b, find the number of redundant substrings of word. Note: A substring is a contiguous group of 0 or more characters in a string. For example- "bcb" is a substring of "abcba", while "bba" is not. Function Description Complete the function getRedundantSubstrings in the editor below. Returns int: the number of redundant substrings

Constraints

  • 1 ≤ |word| ≤ 10⁵
  • -10³ ≤ a ≤ 10³
  • -10³ ≤ b ≤ 10³
  • word contains lowercase English letters, [a-z].
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Developers at Amazon are working on a text generation utility for one of their new products. Currently, the utility generates only special strings. A string is special if there are no matching adjacent characters. Given a string s of length n, generate a special string of length n that is lexicographically greater than s. If multiple such special strings are possible, then return the lexicographically smallest string among them. Notes: Special String: A string is special if there are no two adjacent characters that are the same. Lexicographical Order: This is a generalization of the way words are alphabetically ordered in dictionaries. For example, "abc" is lexicographically smaller than "abd" because 'c' comes before 'd' in the alphabet. A string a is lexicographically smaller than a string b if and only if one of the following conditions holds: a is a prefix of b, but is not equal to b. In the first position where a and b differ, the character in a comes before the character in b in the alphabet. For example, "abc" is smaller than "abd" because 'c' comes before 'd'. Important Considerations: If the character is 'z', it is the last character in the alphabet and cannot be increased further. The string should not wrap around to 'a after 'z' The output string must not have any adjacent characters that are the same. Function Description Complete the function getSpecialString in the editor below. getSpecialString has the following parameter:

  • s: the input string Returns string: the lexicographically smallest string that is greater than s. If no such special string exists, return "-1".

Constraints

  • 1 ≤ |s| ≤ 10⁶
  • s consists of lowercase English letters only.

Example 1

Input:

s = "abbd"

Output:

"abca"

Explanation: Some of the special strings that are lexicographically greater than s are shown - The lexicographically smallest special string that is greater than "abbd" is "abca".

Example 2

Input:

s = "abccde"

Output:

"abcdab"

Explanation: Some of the special strings that are lexicographically greater than s are "abcdde", "abcdab", "abcdbc". The lexicographically smallest special string that is greater than "abcde" is "abcda".

Example 3

Input:

s = "zzab"

Output:

"-1"

Explanation: There is no special string of length 4 that is lexicographically greater than "zzab".

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

A team of financial analysts at Amazon closely monitors revenue generated by a newly launched product. They classify a period of one or more consecutive days as a stable-growth period if the revenue generated by the product takes no more than k distinct values over that period. Given an array revenues of size n, that represents the revenues generated by the new product on n consecutive days, and an integer k, determine the total number of stable growth periods over the n days. Since the answer can be large, return it modulo (10⁹ + 7). Function Description Complete the function getStablePeriodsCount in the editor. getStablePeriodsCount has the following parameters:

  • int revenues[n]: the revenues generated by the new product over n days
  • int k: the maximum number of distinct values in a stable growth period Returns int: the number of stable growth periods of the product over n days, modulo (10⁹ + 7)

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ kn
  • -10⁹ ≤ revenues[i] ≤ 10⁹

Example 1

Input:

revenues = [1, 2, 1]
k = 1

Output:

3

Explanation: There are 3 periods with k=1 or fewer distinct values. The number of stable growth periods is 3.

Example 2

Input:

revenues = [2, -3, 2, -3]
k = 2

Output:

10

Explanation: Any contiguous period of 1 or more days has 2 or fewer distinct values, thus all 10 subarrays represent a period of stable growth

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

Developers at Amazon have their applications deployed on n servers. Initially, the ith server has an id server[i] and can handle server[i] requests at a time. For maintenance purposes, some servers are replaced periodically. On a jth day, all the servers with id equal to replaced[j] are replaced with servers with id newId[j] that can serve newId[j] requests. The total number of requests served on a jth day is the sum of the ids of the servers that the application is running on. Given server, replaced, and newId, find the total number of requests served by the servers each day. Note: The indices i and j are assumed to follow 1-based indexing. Function Description Complete the function getTotalRequests in the editor. getTotalRequests takes the following arguments:

    1. int server[n]: the initial server ids
    1. int replaced[n]: the ids of the servers to replace
    1. int newId[n]: the new ids of the replaced servers Returns int[]: an array of integers representing the total number of requests served each day

Constraints

  • 1 ≤ n ≤ 105
  • 1 ≤ server[i], replacedId[i], newID[i] ≤ 104

Example 1

Input:

server = [20, 10]
replaced = [10, 20]
newId = [20, 1]

Output:

[40, 2]

Explanation: Day 1: The servers are [20, 10]. Server with id 10 is replaced by a server with id 20. New servers are [20, 20]. Total requests = 20 + 20 = 40. Day 2: The servers are [20, 20]. Server with id 20 is replaced by a server with id 1. New servers are [1, 1]. Total requests = 1 + 1 = 2. Hence the answer is [40, 2].

Example 2

Input:

server = [3, 3]
replaced = [3, 1]
newId = [1, 5]

Output:

[2, 10]

Explanation: After the first day, the servers are [1, 1]. After the second day, the servers are [5, 5] :)

Example 3

Input:

server = [2, 5, 2]
replaced = [2, 5, 3]
newId = [3, 1, 5]

Output:

[11, 7, 11]

Explanation: After the first day, the servers are [3, 5, 3].) After the second day, the servers are [3, 1, 3] :) After the third day,the servers are [5, 1, 5] :)

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

Amazon Technical Academy (ATA) provides in-demand, technical training to current Amazon employees looking to broaden their skill sets. ATA has admitted a group of n prospective trainees with varying skill levels. To better accommodate the trainees, ATA has decided to create classes tailored to the skill levels. A placement examination will return a skill level that will be used to group the trainees into classes, where levels[i] represents the skill level of trainee i. All trainees within a class must have a skill level within maxSpread, a specified range of one another. Determine the minimum number of classes that must be formed. Function Description Complete the function groupStudents in the editor. groupStudents has the following parameter(s):

  • int levels[n]: the skill level for each student
  • int maxSpread: the maximum allowed skill level difference between any two members of a class Returns int: the minimum number of classes that can be formed

Constraints

`1 1 <- levels[i] ≤ 10⁹ for every

Example 1

Input:

levels = [1, 4, 7, 3, 4]
maxSpread = 2

Output:

3

Explanation: The trainees in any class must be within maxSpread = 2 levels of each other. In this case, one optimal grouping is (1, 3), (4, 4), and (7). Another possible grouping is (1), (3, 4, 4), (7). There is no way to form fewer than 3 classes.

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

Amazon games is organizing a tournament of pair games where two teams of two players each compete against one another. There are two groups g1 and g2 of size n each. The skill levels of the ith players of the groups are g1[i] and g2[i]. For each pair of indices, (i, j) (0 ≤i g2[i] + g2[j], and vice-versa. Given g1, and g2, find the number of games group1 will win. Since the answer can be large, report it modulo 10⁹ + 7. Function Description Complete the function group1WinCount in the editor. group1WinCount takes the following arguments:

    1. int g1[n]: The skills of the players of group1
    1. int g2[n]: The skills of the players of group2 Returns int: The number of games won by group1 modulo 10⁹ + 7.

Constraints

  • 2 ≤ n ≤ 10⁵
  • 1 ≤ g1[i], g2[i] ≤ 10⁹

Example 1

Input:

g1 = [1, 2, 3]
g2 = [3, 2, 1]

Output:

1

Explanation: Suppose n = 3, g1 = [1, 2, 3], and g2 = [3, 2, 1]. [Table showing: Pair | group1 | group2 | Winner (0, 1) | [1, 2] | [3, 2] | group2 (0, 2) | [1, 3] | [3, 1] | - (1, 2) | [2, 3] | [2, 1] | group1] group1 wins one match so the answer is 1.

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

Database security and authentication have become vital due to the increasing number of cyberattcks every day. Amazon has created a team for the analysis of various types of cyberattacks. In one such analysis, the team finds a virus that attacks the user passwords. The virus designed has an attacking rule defined by attackOrder, which is a permutation of length n. In the i-th second of the attack, the virus attacks at the attackOrder[i]-th character of the password, replacing it with the malicious character '' (source img too blurry, it looks like '' to me, if not, pls lmk, I am happy to modify accordingly! You are the best! Thanks a lot!), i.e, pwassword[attackOrder[i]] = '' after the i-th second. The password is said to be irrecoverable when the number of surroundings of the password containing at least one malicious character '' becomes greater than or equal to n. In order to estimate the threat posed by the virus, the team wishes to find the min time after which the password becomes irrecoverable. Note: If the password is irrecoverable at the start, report 1 as the answer. A substring of a string s is a contiguous segment of that string. Function Description Complete the function helpAmazonFindMinTimeAgain in the editor. helpAmazonFindMinTimeAgain has the following parameter:

  • string password: the inital password
  • int attackOrder[]: permutation arr of integers [1, 2,.., n]
  • int m: the recoverability parameter Returns int: the minimum time after which the password becomes irrecoverable.

Constraints

1 ≤ n ≤ 8 * 10⁵ String password consists of lowercase English chars 1 ≤ attackOrder[i] ≤ n 0 ≤ m ≤ n * (n + 1) / 2

Example 1

Input:

pwd = "bcced"
attackOrder = [2, 3, 1, 4, 5]
m = 10

Output:

2

Explanation: After the first second, the password becomes The 8 substrings that contain at least one malicious character are ["b*", "bc", "bce", "bced", "", "c", "ce", "ced"] and 8 is less than m. After 2nd second, the password becomes: The 11 substrings that containt at least one malicious character are ["b", "b", "be", "bed", "", "**", "**e", "**ed", "", "e", "ed"]. This is greater or equal to m. After the replacement at second 2, the number of substrings is at least m. The answer is 2. Helloo - I've triple-checked the text, but since the source image is too blurry, if you still find any mistakes, please let me know! I'm more than happy to correct them. Thank you so much! Another source found on the internet - Updated on 05-31-2025 - There is a password of length n = 5, password = "bcced". The 1-based indices where characters will be replaced, attackOrder = [2, 3, 1, 4, 5], and the recoverability parameter m = 10. (1.) After the 1st second, the password becomes: b * c e d —— There are 8 substrings that contain at least one malicious character: ["b", "bc", "bce", "bced", "", "c", "ce", "ced"]. 8 is less than m. (2.) After the 2nd second, the password becomes: b * * e d —— There are 11 substrings that contain at least one malicious character: ["b", "b", "be", "bed", "", "", "**e", "**ed", "", "*e", "*ed"]. 11 is greater than or equal to m. After the replacement at 2nd second, the number of substrings is at least m. The answer is 2.

Example 2

Input:

pwd = "abcd"
attackOrder = [4, 1, 3, 2]
m = 10

Output:

4

Explanation: This test case was added on 06-03-2025. Relevant source ss was included in the Problem Source section below.

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

note - Scrolling down to the vely bottom of the page to the Problem Source section to see the original problem description~ In a magical realm, Amazon Games is hosting an enchanting tournament where two teams, each comprised of two brave players, battle for glory. These teams are known as group1 and group2, each filled with skilled warriors whose abilities are represented by arrays: the skill of each player in group1 is denoted as group1[], while in group2, it is group2[]. As the tournament unfolds, every possible pair of players from both groups is summoned to compete; specifically, the combined strength of players from group1 (i.e., group1[] + group1[]) is pitted against the combined might of players from group2 (i.e., group2[] + group2[]). Your quest is to determine how many matches group1 will triumph in, while ensuring that the final count is reported with a sprinkle of magic, modulo 10⁹ + 7

Constraints

  • 2 ≤ n ≤ 10⁵
  • 1 ≤ group1[i], group2[i] ≤ 10⁹

Example 1

Input:

n = 3
firstTeam = [1, 2, 3]
secondTeam = [3, 2, 1]

Output:

1

Explanation: As shown on the iamge above, group1 wins one match so the answer is 1.

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

Within Amazon’s vast fulfillment system, there exist n distinct inventory tasks, each operated by bots[i] bots. These tasks compete, leading to conflict rounds every minute where two random tasks are chosen. During each conflict: The task with more bots defeats the other and absorbs all of its bots. If both tasks have an equal number of bots, one is randomly chosen as the winner and takes over the losing task’s bots. This sequence continues until only one inventory task remains active. Your objective is to determine which of these tasks have a chance to survive as the final remaining task in at least one possible sequence of events. Return the 1-based indices of all such tasks, and also please sort it in ascending order . p.s. if you are applying for a L5 position, you may not want to miss this question.. Gooood news! We might found the shoe selling question: Selling Shoes The second question in the same batch..Will update once find reliable source..like always~~

Constraints

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

Example 1

Input:

n = 5
bots = [1, 6, 2, 7, 2]

Output:

[2, 4]

Explanation: The inventory task at position 2 can potentially survive by following these possible clashes (where bots[i] = 0 indicates that its bots have been absorbed by another task): First, the 2nd task defeats the 1st task, acquiring its bots and increasing its count to 6 + 1 = 7. The updated bots array becomes [0, 7, 2, 7, 2]. Next, it eliminates the 3rd task, boosting its total to 7 + 2 = 9. The bots array is now [0, 9, 0, 7, 2]. Afterward, it overpowers the 4th task, raising its bot count to 9 + 7 = 16. The bots array updates to [0, 16, 0, 0, 2]. Finally, it conquers the 5th task, reaching a total of 16 + 2 = 18 bots. The final state is [0, 18, 0, 0, 0].

Similarly, the inventory task at position 4 can also manage to be the last remaining after these rounds: Initially, the 4th task absorbs the 1st task, collecting its bots to get 7 + 1 = 8. Now the bots array reads [0, 6, 2, 8, 2]. Then, it overtakes the 3rd task, increasing its count to 8 + 2 = 10. The bots array becomes [0, 6, 0, 10, 2]. Following that, it defeats the 2nd task, resulting in a total of 10 + 6 = 16 bots. Updated bots: [0, 0, 0, 16, 2]. Lastly, it overcomes the 5th task, boosting its final count to 16 + 2 = 18. The final bots array is [0, 0, 0, 18, 0]. Therefore, inventory tasks 2 and 4 have the potential to survive until the end in at least one scenario. All other tasks will be eliminated eventually in every possible sequence.

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

The developers at Amazon are developing a regex matching library for their NLP use cases. A prototype regex matching has the following requirements: The regex expression contains lowercase English letters, '(', ')', '.', and ''. '.' matches with exactly one lowercase English letter. A regular expression followed by '' matches with zero or more occurrences of the regular expression. If an expression is enclosed in parentheses '(' and ')', it is treated as one expression and any asterisk '' applies to the whole expression. It is guaranteed that no expression enclosed within parenthesis contains any '' but is always followed by ''. Also, there is no nested brackets sequence in the given regex expression for the prototype. For example, Regex "(ab)d" matches with the strings "d", "ababd", "abd", but not with the strings "abbd", "abab". Regex "abd" matches with the strings "abbbd", "ad", "abd", but not with strings "ababd". Regex "a(b.d)" matches with the strings "abcdbcd", "abcdbed", "abed", "a" but not with strings "bcd", "abd". Regex "(.)*" matches with the strings "a", "aa", "aaa", "b", "bb" and many more but not "ac", "and", or "bcd" for example. Given an array, arr, of length k containing strings consisting of lowercase English letters only and a string regex of length n, for each of them find whether the given regex matches with the string or not and report an array of strings "YES" or "NO" respectively. Function Description Complete the function isRegexMatching in the editor. isRegexMatching has the following parameters:

  • regex: A regex
  • arr[k]: An array of strings Returns string[]: An array of strings of size k where the ith string is "YES" if the ith string in arr matches with regex, otherwise it is "NO".

Constraints

N/A

Example 1

Input:

regex = "ab(e.r)*e"
arr = ["abbeere", "abefretre"]

Output:

["NO", "YES"]

Explanation: Here, n = 9, regex = "ab(e.r)*e", k = 2, arr = ["abbeere", "abefretre"]

  • arr[0] = "abbeere" doesn't match the regex "ab(e.r)*e".
  • arr[1] = "abefretre" matches the regex "ab(e.r)e", if we replace '' with 2 occurrences of "e.r", i.e. it becomes "abe.re.re". Now, replace both '.' with 'f' and 't' respectively. Hence, the answer is ["NO", "YES"].

Example 2

Input:

regex = "..()*e*"
arr = ["code", "abeee", "cd"]

Output:

["NO", "YES", "YES"]

Explanation: Here, n = 8, regex = "..()*ex", k = 3, arr = ["code", "abeeee", "cd"]

  • arr[0] = "code" doesn't matches the regex "..()*ex".
  • arr[1] = "abeeee" matches the regex "..()ex", if we replace first '' with 0 occurrences of "" (an empty string) and second '*' with 3 occurrences of "e", i.e. it becomes "..eee". Now, replace both '.' with 'a' and 'b' respectively.
  • arr[2] = "cd" matches the regex "..()ex", if we replace first '' with 0 occurrences of "" and second '*' with 0 occurrences of "e", i.e. it becomes "..". Now, replace both '.' with 'c' and 'd' respectively. Hence, the answer is ["NO", "YES", "YES"].
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Data scientists at Amazon are working on a utility for genome sequencing algorithms that look for palindromic patterns in DNA sequence strings. A DNA sequence string is considered special if it can be divided into two non-empty substrings such that the resulting strings can be rearranged to form palindromes after removing at most one character from each of them. Given a string, dna_sequence, return the string "YES" if it is a special sequence and "NO" otherwise. Note: A substring is defined as any contiguous segment of a string. A palindrome is a string that reads the same forwards and backwards such as "abccba", "aba", "b", and "ccc". Function Description Complete the function isSpecialSequence in the editor below. isSpecialSequence takes the following arguments:

  • str dna_sequence: the given string of dna sequence Returns string: "YES" if the given sequence is special and "NO" otherwise

Constraints

  • 1 ≤ length(dna_sequence) ≤ 3 * 10⁵
  • It is guaranteed that the sequence consists of lowercase English characters only.

Example 1

Input:

dna_sequence = "abcad"

Output:

"YES"

Explanation: Thus the answer is "YES".

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

Given an array arr of integers, an integer m (window size), and an integer k, for every contiguous subarray of length m return the k-th smallest element. The result has length arr.length - m + 1.

Constraints

  • 1 ≤ k ≤ m ≤ arr.length ≤ 10⁵
  • -10⁹ ≤ arr[i] ≤ 10⁹

Example 1

Input:

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

Output:

[3, 2]

Explanation: In the first subarray of size 3 ([3,1,4]) the 2nd smallest element is 3. In the second subarray of size 3 ([1,4,2]) the 2nd smallest element is 2.

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

Amazon's fulfillment centers handle packages of various weights, and they need to optimize their sorting process. Given an array weight which denotes the weights of n packages, the goal is to create the lexicographically maximal resulting array sorted by non-increasing order of weight using the following operations: Discard the first package from the current weight array Add the first element to the resulting array, then remove it along with the next k (a fixed constant) elements from the current array Note that Operation 2 can also be applied when fewer than k elements remain after the current element; In that case, the entire remaining array is removed. The resulting array must have packages arranged in non-increasing weight order. Given an array weight of size n and an integer k, find the lexicographically maximal resulting array sorted by non-increasing order of weight that can be obtained. Note: An array x is lexicographically greater than an array y if: x[i] > y[i], where i is the first position where x and y differ, or |x| > |y| and y is a prefix of x (where |x| denotes the size of array x) Function Description Complete the function lexicographicallyMaximalResultingArray in the editor. lexicographicallyMaximalResultingArray has the following parameters:

  • int weight[n]: an array of integers representing the weights of packages
  • int k: an integer representing the fixed constant Returns int[]: the lexicographically maximal resulting array sorted in non-increasing order of weight

Example 1

Input:

k = 1
weight = [4, 3, 5, 5, 3]

Output:

[5, 3]

Explanation: After performing the above operation, the resulting array is [5, 3]. It is guaranteed that no other resulting array sorted in non-increasing order can be formed that is lexicographically larger than [5, 3]. So we return it as our final answer for this test case from the test given by a tech firm called Amzoan. This test case was added on 04-27-2025 (how time flies! we’ve already completed 25% of 2025!!). Like always, you can find the relevant ss from the Problme Source below. Lastly and most importantly, I'd like to express my sincere gratitude to the friend who shared this test case with us. Thank you so much for your support! I wouldn't find this test case without your help!

Example 2

Input:

k = 2
weight = [10, 5, 9, 2, 5]

Output:

[10, 5]

Explanation: :)

Example 3

Input:

k = 0
weight = [3]

Output:

[3]

Explanation: In this case since there is only 1 element, we apply Operation 2, adding weight[0] = 3 to the resulting array, which gives the lexicographically maximal array sorted in non-increasing order of weight. Thus, the answer is [3].

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

Giv

Constraints

A mysterious untelling for now As always, will add once find out

Example 1

Input:

s = "a?rt???"

Output:

"aartraa"

Explanation: Question marks can be replaced by a, r, a, a and we can make it palindrome.

Example 2

Input:

s = "bx??tm"

Output:

"-1"

Explanation: No character can be added to make it a palindrome.

Example 3

Input:

s = "ai?a??u"

Output:

"aaiuiaa"

Explanation: '?' is replaced by a, a and i and characters are rearranged to make it a palindrome.

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

Developers at Amazon continuously develop algorithms to ensure the security of users' accounts through strong passwords. One such algorithm is based upon the concept of perfect anagrams.

  • A string x is an anagram of y if it is possible to rearrange the letters in x to get y. For example, "bat" and "tab" are anagrams, 'bats' and 'tab' are not.
  • Two strings a and b are said to be perfect anagrams if a and b are anagrams of each other and a is not equal to b. For example, Strings "dog" and "god" are anagrams and perfect anagrams. Strings "baba" and "baba" are anagrams but not perfect anagrams because the strings are equal. Strings "abbac" and "caaba" are not anagrams because they do not contain exactly the same characters. Given a string s, find the maximum length of two of its substrings that are perfect anagrams. If no such substrings exist, return -1. Note: A substring is a contiguous subsegment of a string. For example, "xy" is a substring of "xyz" but "xz" is not. Function Description Complete the function longestPerfectAnagrams in the editor. longestPerfectAnagrams has the following parameter:
  • string s: a string Returns int: the length of the longest substring pair which are perfect anagrams or -1 if no such pair exists.

Constraints

  • 1 ≤ |s| ≤ 10⁵
  • string s contains lowercase English characters only.

Example 1

Input:

s = "abcacb"

Output:

4

Explanation: The string s = "abcacbab",

  • Pairs of substrings such as ("ca", "ac"), ("abc", "acb"), ("bca", "acb"), ("bcac", "cacb"), etc. are perfect anagrams.
  • Among these, the longest are ("bcac", "cacb"). It can be proven that no two substrings of length greater than 4 in the given string are perfect anagrams. Return 4.

Example 2

Input:

s = "cabcab"

Output:

3

Explanation: ("cab","bca") , ('abc,'bca'') are two such 3 length substrings

Example 3

Input:

s = "aabbcc"

Output:

-1

Explanation: There are no perfect anagram. a & a , b&b , c& c are exctly same.

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

An Amazon warehouse manager is responsible for managing inventory and ensuring that each product has a unique identifier. There are n products in the warehouse, where the identifier of the i-th item is represented by the array identifier[i]. However, in the inventory management system, some items have the same identifier. To make all items in the inventory distinct, the following operation can be used:

  • Remove the first (leftmost) item from the inventory sequence. Given n products and the array identifier, find the minimum number of operations required to make all items in the inventory distinct. Function Description Complete the function makeAllElementsDistinct in the editor. makeAllElementsDistinct has the following parameters:
    1. n: the number of products
    1. int identifier[n]: an array of integers representing the identifiers Returns int: the minimum number of operations required to make all the elements of the array distinct
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Problem Description Version No.2: You are given two arrays size and cost of size n. The cost will be calculated for every increment. Your task is to make the size array distinct by incrementing any of its elements and calculate the minimum cost to do so. Function Description Complete the function makeArrayDistinct in the editor. makeArrayDistinct has the following parameters:

    1. int[] size: an array of integers representing the sizes
    1. int[] cost: an array of integers representing the costs Returns int: the minimum cost to make the size array distinct
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given a non-negative integer array nums. In one operation, you must:

  • Choose a positive integer x such that x is less than or equal to the smallest non-zero element in nums.
  • Subtract x from every positive element in nums. Return the minimum number of operations to make every element in nums equal to 0.

Constraints

  • 1 ≤ nums.length ≤ 100
  • 0 ≤ nums[i] ≤ 100

Example 1

Input:

nums = [1,5,0,3,5]

Output:

3

Explanation: In the first operation, choose x = 1. Now, nums = [0,4,0,2,4] In the second operation, choose x = 2. Now, nums = [0,2,0,0,2] In the third operation, choose x = 2. Now, nums = [0,0,0,0,0]

Example 2

Input:

nums = [0]

Output:

0

Explanation: Each element in nums is already 0 so no operations are needed.

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

You are given an integer array arr. In one operation, choose two values x and y, and replace every occurrence of x in the array with y. An array is called contiguous by value if, for every distinct value, all occurrences of that value appear in one uninterrupted block. Return the minimum number of operations needed to make the array contiguous by value. Function Description Complete the function minOperationsToMakeValuesContiguous in the editor below. minOperationsToMakeValuesContiguous has the following parameter:

  • int[] arr: the input array Returns int: the minimum number of replacement operations.

Constraints

  • Each operation replaces all occurrences of one chosen value globally.
  • After the final array is formed, each distinct value must appear in a single block.

Example 1

Input:

arr = [1, 2, 1]

Output:

1

Explanation: Replace every 2 with 1 to get [1, 1, 1].

Example 2

Input:

arr = [1, 2, 3]

Output:

0

Explanation: Every value already occupies a single contiguous block.

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

Amazon is developing an efficient string matching library. Develop a prototype service that matches a simple pattern with a text. There are two arrays of strings, text, and pat, each of size n. Each string in pat is a regex expression that contains exactly one wildcard character (). A wildcard character () matches any sequence of zero or more lowercase English letters. A regex matches some string if it is possible to replace the wildcard character with some sequence of characters such that the regex expression becomes equal to the string. No other character can be changed. For example, regex "abc*bcd" matches "abcbcd", "abcefgbcd" and "abccbcd" whereas it does not match the strings "abcbd", "abzbcd", "abcd". For every i from 1 to n, your task is to find out whether pat[i] matches text[i]. Return the answer as an array of strings of size n where the i^th string is "YES" if pat[i] matches text[i], and "NO" otherwise. Note: The implementation shall not use any in build regex libraries. Function Description Complete the function matchStrings in the editor below. matchStrings has the following parameters: String text[n]: the strings to test String pat[n]: the patterns to match Returns String[n]: "YES" or "NO" answers to the queries

Constraints

  • 1 ≤ n ≤ 10
  • 1 ≤ |text[i]|, |pat[i]| ≤ 10⁵
  • text[i] contains only lowercase English characters.
  • pat[i] contains exactly one wildcard character and other lowercase English characters.

Example 1

Input:

text = ["code", "coder"]
pat = ["co*d", "co*er"]

Output:

["NO", "YES"]

Explanation: Given n = 2, text = ["code", "coder"], pat = ["co*d", "co*er"],

  • text[0] = "code", pat[0] = "co*d", "NO", the suffixes do not match
  • text[1] = "coder", pat[1] = "co*er", "YES", the prefixes and suffixes match Here prefix of a string is defined as any substring that starts at the beginning of the string and suffix of a string is defined as any substring that ends at the end of the string. Return ["NO", "YES"].

Example 2

Input:

text = ["hackerrank", "hackerrnak"]
pat = ["hac*rank", "hac*rank"]

Output:

["YES", "NO"]

Explanation: The prefixes and suffixes must match. The suffix in text[1] is "rnak".

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

There are n unique categories of goods. You are given an array inventory of length n, where inventory[i] denotes the count of items available for category i (with i ranging from 0 to n - 1). These goods need to be organized into groups for delivery. Group Packing Conditions: No two items within a single group can belong to the same category — every item in a group must be of a distinct category. The count of items placed in the current group must be strictly greater than the count in the previous group. Each item can be used only once, and it is not mandatory to pack all items. Goal: Calculate the maximum number of groups that can be created for delivery based on the above conditions.

Example 1

Input:

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

Output:

4

Explanation: The initial bundle holds 1 unit from type 4. Leftover stock: [2, 3, 1, 4, 1] The second bundle packs 2 units from types 0 and 1. Remaining stock: [1, 2, 1, 4, 1] The third bundle consists of 3 units from types 0, 1, and 3. Remaining stock: [0, 1, 3, 1] The fourth bundle carries 4 units from types 1, 2, 3, and 4. Remaining stock: [0, 0, 0, 2, 0] So we get 4 as our expected output :)

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

AMZ Interval Collection (A group of problems focused on operations involving intervals :) -

  1. Get Maximum Sum Find Overlapping Times (Full-Time)
  2. Find Overlapping Times (Intern)
  3. Merge Intervals (Intern, NG)
  4. Task Scheduler (Full-Time)
  5. Optimal Interval Difference Given 3 arrays - Array 1 = Start times Array 2 = Durations Array 3 = Costs Some intervals might overlap. Find the maximum sum of Non-Overlapping intervals.

Example 1

Input:

starts = [4, 2, 7, 8]
durations = [3, 2, 3, 2]
costs = [7, 3, 1, 2]

Output:

9

Explanation: Reason : Based on the given data, the intervals are [2,4], [4,7], [7,10] and [8,10] Non overlaping intervals are: [2,4],[7,10] and [4,7],[8,10] Considering [2,4] + [7,10] = 3 + 1 = 4, Considering [4,7] + [8,10] = 7 + 2 = 9 Answer is 9.

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

You are in the Amazon's Cloud Infrastructure Team, and you are working on a project to optimize how data flows through its network of storage servers. You are given with n storage servers, and the throughput capacity of each server is given in an integer array named throughput. There are pipelineCount data pipelines that need to be connected to two storage servers, one as the primary connection and the other as the backup. Each data pipeline must choose a unique pair of servers for its connections. The transferRate for each data pipeline is defined as the sum of the throughput of its primary and backup servers. Given an integer array throughput and an integer pipelineCount, find the maximum total transferRate that can be obtained by optimally choosing unique pairs of connections for each data pipeline. Note:

  • A pair of servers (x, y) is said to be unique if no other pipeline has selected the same pair. However, the pairs (y, x) and (x, y) are treated as different connections.
  • It is also possible to select the same server for primary and backup connections, which means that (x, x) is a valid pair for the connection. Function Description Complete the function maxTransferRate in the editor. maxTransferRate has the following parameters:
    1. int throughput[n]: array of throughput provided by each server instance.
    1. int pipelineCount: the number of data pipelines that need to be connected. Returns long: the maximum total transfer rate.

Example 1

Input:

throughput = [4, 2, 5]
pipelineCount = 4

Output:

36

Explanation: The data pipelines can select their connection among the following 9 possible server pairs: [1, 1], [1, 2], [1, 3], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3] (Assuming 1-based indexing of throughput array). However, each data pipeline must select a unique pair of servers. To achieve the maximum total transferRate, the data pipelines can optimally choose the pairs [3, 3], [1, 3], [3, 1], [1, 1] to obtain the maximum sum of transferRate = (5 + 5) + (5 + 4) + (4 + 5) + (4 + 4) = 36.

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

There are n servers, where the power of the jth server is given by arr[j]. These servers are grouped into clusters of size three. The power of a cluster, denoted as cluster_power, is defined as the median of the power values of the three servers in the cluster. Each server can be part of at most one cluster, and some servers may remain unused. The total system power, called max_result, is the sum of the power of all the clusters formed. The task is to find the maximum possible max_result. Function Description Complete the function maximizeClusterPower in the editor. maximizeClusterPower has the following parameters:

    1. int n: the number of servers
    1. int[] arr: an array of integers representing the power of each server Returns int: the maximum possible system power
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

As part of your Day 1 orientation at Amazon, your new team is hosting a programming challenge. You've been asked to participate in completing the following task. Given an array of integers, perform certain operations in order to satisfy some constraints. The constraints are as follows:

  • The first array element must be 1.
  • For all other elements, the difference between adjacent integers must not be greater than 1. In other words, for 1 ≤ i To accomplish this, the following operations are available:
  • Rearrange the elements in any way.
  • Reduce any element to any number that is at least 1. What is the maximum value that can be achieved for the final element of the array by following these operations and constraints?

Example 1

Input:

arr = [3, 1, 3, 4]

Output:

4

Explanation:

  1. Subtract 1 from the first element, making the array [2, 1, 3, 4].
  2. Rearrange the array into [1, 2, 3, 4].
  3. The final element's value is 4, the maximum value that can be achieved. Therefore, the answer is 4.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

The engineering team at an Amazon fulfillment center is optimizing their performance system where each printer can print pages/number of pages. Each printer can be in exactly one of three states: operational, idle, or suspended. Printers initially start in an idle state and can be activated one by one However, all running printers cannot run at once, some will get suspended due to their threshold rules defined by the suspension rule Suspension Rule: If there are at least x operational printers, all such printers i (with threshold[i] Task: The goal is to determine the maximum number of pages that can be printed before printers get suspended. Note: Activating a printer with threshold[i] = x allows it to print pages[i] pages. However, once at least x printers are active, their pages gets printed first, and then all printers with threshold Choosing the activation order carefully is curcial to maximize the total printed pages before suspensions occur.

Example 1

Input:

pages = [4, 1, 5, 2, 3]
threshold = [3, 3, 2, 3, 3]

Output:

14

Explanation: The optimal way to maximize the number of pages printed is as follows (assuming 1-based indexing):

  • Turn on the 4th printer which prints 2 pages. Since the number of operational printers is 1 and it hasn't reached the threshold for any printer, no printer is suspended.
  • Next, turn on the 3rd printer which prints 5 pages. Now, there are 2 operational printers. Since the threshold for printer 3 is threshold[3] = 2, printer 3 gets suspended and stops functioning. So, now we have one printer which is the 4th printer.
  • Turn on the 1st printer which prints 4 pages. There are now 2 operational printers, and printer 1 remains functional as its threshold is threshold[1] = 3.
  • Finally, turn on the 5th printer which prints 3 pages. Now, there are 3 operational printers (printer 1, 4, and 5). Since all the remaining thresholds (1, 2, 4) are all less than or equal to 1, both printer 3 and printer 2 remain functioning. Thus, the total number of pages printed is: 2 (from printer 4) + 5 (from printer 3) + 4 (from printer 1) + 3 (from printer 5) = 14 pages.

Example 2

Input:

pages = [2, 4, 4, 4, 5, 3]
threshold = [1, 3, 1, 3, 3, 2]

Output:

20

Explanation: The optimal way to maximize the number of pages printed is as follows - (Assuming 1-based indexing :)

  1. Turn on the 3rd printer, which prints 4 pages. At this point, since there are 1 operational printer and the thresholds for pinter 1 and 3 are 1, both printers 1 and 3 gets suspended and stop functioning. So, now we have 0 operational printer.
  2. Next, turn on the 2nd printer, which prints 4 pages. No printers are suspended since the number of operational printers (equal to 1) is within the threshold.
  3. Turn on the 6th printer, which prints 3 pages. Operational printers become equal to 2. Printer 6 gets suspended and stops working as its threshold is 2, and now there i only 1 operational printer (the 2nd one :(
  4. Turn on the 4th printer, which prints 4 pages. Number of operational printers become equal to 2.
  5. Finally, turn on the 5th printer, which prints 5 pages. Now printer 2, 4, and 5 gets suspended and stop working as there are 3 operational printers, and their threshold are less than or equal to 3. So, the total number of pages printed is -- 4 (from pinter 3) + 4 (from printer 2) + 3 (from printer 6) + 4 ... = 20

Example 3

Input:

pages = [2, 6, 10, 13]
threshold = [2, 1, 1, 1]

Output:

15

Explanation: The optimal way to maximize the number of pages printed is as follows - (Assuming 1-based indexing :)

  1. First, the engineers decide to activate the 4th printer, which prints 13 pages. At this point, the total number of operational printers is 1. The printing of 13 pages is completed first, followed by the suspension of any printers exceeding their threshold.
  2. Next, since the threshold for printers 2, 3, and 4 is 1, and there is now 1 operational printer (4th printer), these printers become damaged. So, all the printers (2nd, 3rd, 4th) with threshold = 1, gets suspended and stop working.
  3. Later, the only printer the team can turn on is printer 1. By activating printing 1, they print 2 more pages. The number of operational printer is now 1, and because threahold[1] = 2, printer 1 will not be suspended and remains functional. So, the total number of pages printed is 13 (from printer 4) + 2(from printer 1) = 15. we return 15.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

At Amazon, a user owns a unique tool called the "Parentheses Perfection Kit." This kit contains different types of parentheses, each with a specific efficiency rating. The goal is to create a balanced sequence of parentheses by adding zero or more parentheses from the kit to maximize the sequence's total EfficiencyScore. The EfficiencyScore of a sequence is the sum of the efficiency ratings of the parentheses used from the kit. A sequence is considered balanced if it has an equal number of opening ( and closing ) parentheses, with each opening parenthesis properly matched with a closing one in the correct order (i.e., circular balance). For instance, sequences like (), (()), and (()()) are balanced, while sequences like ), ()(, and ())( are not. You are given an initial parentheses sequence represented by the string s, along with a Parentheses Perfection Kit containing different types of parentheses in the form of the string kitParentheses and their respective efficiency ratings in the efficiencyRatings array (both of size m). The EfficiencyScore of the original string s is initially 0. You can use any number of unused parentheses from the kit to create the final sequence, as long as the final sequence remains balanced. The task is to determine the maximum possible EfficiencyScore that can be achieved for the resulting balanced sequence. It is guaranteed that the sequence can be made balanced by adding zero or more parentheses from the kit. Function Description Complete the function maximizeEfficiencyScore in the editor. maximizeEfficiencyScore has the following parameters:

    1. String s: the initial parentheses sequence
    1. String kitParentheses: the parentheses available in the kit
    1. int[] efficiencyRatings: the efficiency ratings of the parentheses in the kit Returns int: the maximum possible EfficiencyScore

Example 1

Input:

s = ")(("
kitParentheses = ")(()))"
efficiencyRatings = [3, 4, 2, -4, -1, -3]

Output:

6

Explanation:

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

There are n components, and the performance level of each component is represented by performance[0], performance[1], ..., performance[n-1]. Let's define a partition (l, r) as the group of components indexed from l to r. To identify and resolve potential bottlenecks in the system, the engineer needs to compute the bitwise AND operation for all components within a partition. The bottleneck level of a partition (l, r) is expressed as: f(l,r) = performance[l] & performance[l+1] & ... & performance[r] Here, the & operator represents the bitwise AND operation. The goal of the engineers is to divide the components into contiguous partitions, ensuring each component belongs to exactly one partition. The objective is to minimize the total bottleneck level of the partitions while maximizing the number of partitions. Given an integer array performance of size n, determine the maximum number of partitions that can be achieved while minimizing the total bottleneck levels of the partitions.

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

BREAKING! Its sister question was found --> Checkout LC 343. Integer Break Input Format The first line of input contains an integer N, representing the number of nodes in the mystical tree. The next N-1 lines each contain two space-separated integers U and V, signifying an edge between the respective nodes. Output Format Print a number X, representing the maximum product of subtree sizes achievable after edge deletions.

Example 1

Input:

w = 5
edges = [[1, 2], [2, 3], [3, 4], [4, 5]]

Output:

6

Explanation: Cut the 3-4 edge. Subtrees formed are 1-2-3 and 4-5, so the product is 3 * 2 = 6.

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

You are given n cities arranged in a line. City i has population population[i] and may contain a security unit described by unit[i], where unit[i] = '1' means a unit is initially stationed in city i. Each security unit may stay where it is, or if it is not in the first city, it may move exactly one city to the left. Every unit can move at most once. After all moves are chosen, a city is protected if at least one security unit is stationed there. Return the maximum total population of all protected cities. Function Description Complete the function maximizeProtectedPopulation in the editor below. maximizeProtectedPopulation has the following parameters:

  • int[] population: the city populations
  • String unit: the initial security-unit layout Returns long: the maximum total population of protected cities.

Constraints

  • population.length = unit.length()<

Example 1

Input:

population = [10, 5, 8, 9, 6]
unit = "01101"

Output:

27

Explanation: Move the unit from city 2 to city 1, keep the unit in city 3, and keep the unit in city 5. Cities 1, 3, and 5 are then protected, for a total population of 10 + 8 + 9 = 27.

Example 2

Input:

population = [7, 4]
unit = "01"

Output:

7

Explanation: Move the only unit left from city 2 to city 1. Protecting city 1 yields the larger total population.

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

In managing tasks at analytics platform, the goal is to efficiently schedule both primary and secondary tasks within specified time constraints. There are n primary tasks and n secondary tasks. Two arrays, primary and secondary, provide information on task hours, where primary[i] represents the duration in hours of the ith primary task, and secondary[i] represents the duration in hours of the ith secondary task. Each day on the platform has a time limit denoted as limit hours. One primary task must be scheduled each day. If time remains after the primary task, you can choose to schedule at most one secondary task on that day. It's essential to ensure that the total hours does not exceed the specified limit hours. Determine the maximum number of secondary tasks that can be scheduled during these n days while adhering to the given constraints.

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

In the world of Amazon's vast inventory management, you face a challenge of optimizing two inventories, inv1 and inv2, each containing n elements. Your goal is to maximize the similarity between these inventories. The similarity is measured by the number of indices i (0 ≤ i Select two distinct indices i and j (where 0 ≤ i, j Apply the operation: add 1 to inv1[i] and subtract 1 from inv1[j]. Using the Inventory Optimizer, you can perform this operation any number of times (including zero) to maximize the similarity between inv1 and inv2. Thanks A LOT! spike!!

Constraints

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

You are given a mystical tree with n nodes. Each node is connected to at least one other node by an edge. Your task is to sever one or more edges in the tree to split it into subtrees. The goal is to maximize the product of the sizes of these subtrees. The size of a subtree is defined as the number of nodes it contains. The product of subtree sizes is calculated by multiplying the sizes of all subtrees together. Write a program that takes as input the number of nodes in the tree and the edges between them, and outputs the maximum product of subtree sizes achievable after severing edges in the tree. Input Format The first line of input contains an integer N, representing the number of nodes in the mystical tree. The next N-1 lines each contain two space-separated integers U and V, signifying an edge between the respective nodes. Output Format Print a number X, representing the maximum product of subtree sizes achievable after edge deletions.

Constraints

N/A

Example 1

Input:

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

Output:

6

Explanation: N/A

Example 2

Input:

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

Output:

2

Explanation: N/A

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

You have an array of data (index starting from 1) data = [3, 6, 1, 4, 2]. Rearrange the data such that after the permutation, 1 * data[1] + 2 * data[2] + 3 * data[3] + ... n * data[n] is the largest. Return the permutations as an array where each element represents the index after permutation (also starting from 1). If there are multiple equivalent answers, return the lexicographically smallest one. Function Description Complete the function maximizeSum in the editor. maximizeSum has the following parameter:

  • int[] data: an array of integers Returns int[]: the permutation of indices that maximizes the sum

Constraints

:O

Example 1

Input:

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

Output:

[3, 5, 1, 4, 2]

Explanation: The permutation [3, 5, 1, 4, 2] is chosen because the sum 1 * 1 + 2 * 2 + 3 * 3 + 4 * 4 + 5 * 6 is the largest sum you can get. Larger values stay later. Sort the array based on 1. value 2. if there's a tie, based on index.

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

You are given an array of integers. Your task is to maximi

Example 1

Input:

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

Output:

17

Explanation: Steps:

  • Choose 5 from [4, 4, 8, 5, 3, 2]
  • Remove 4 and 2
  • Total sum = 5
  • Choose 4 from [4, 8, 5, 3]
  • Remove 4 and 3
  • Total sum = 5 + 4 = 9
  • Choose 8 from [8, 5]
  • Remove 8 and 5
  • Total sum = 9 + 8 = 17
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given an array A of integers and an integer K, you may negate up to K elements of the array. Return the maximum value of the smallest prefix sum after the operations (or equivalently, maximize the array configuration so all prefix sums are positive).

Constraints

  • 1 ≤ N ≤ 10⁵
  • 1 ≤ K ≤ N
  • -10⁹ ≤ A[i] ≤ 10⁹

Example 1

Input:

A = [4, 1, 1, 1]

Output:

3

Explanation: We can apply only at-most 3 negate operations, to make A = [4, -1, -1, -1], after the negate operation, The prefix sums of A, p(A) = [4, 3, 2, 1] which are all positive. So that the answer for A is 3.

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

The developers at Amazon are working on optimising the capacity of their cloud system. In the system, there are n servers where the memory capacity of the i-th server is represented by the array memory[i]. A system always contains an even number of servers. If the system has 2x servers, then x of them will be primary and the other x will be backup servers. For each primary server P, there exists a backup server B where the memory capacity of B ≥ memory capacity of P. The system's memory capacity is the sum of the memory capacity of all the primary servers. Given n servers and an array memory, find the maximum system memory capacity that can be formed using the n servers. Function Description Complete the function maximumCapacity in the editor below. maximumCapacity has the following parameter:

  • int memory[n]: the memory capacity of the given servers Returns long int: the maximum system memory capacity

Constraints

  • 2 ≤ n ≤ 2*10⁵
  • 1 ≤ size[i] (I guess it is supposed to be memory[i] :) ≤ 10⁹

Example 1

Input:

memory = [1, 2, 1, 2]

Output:

3

Explanation: Here, we have 4 servers [serverA, serverB, serverC, serverD] having memory sizes as [1, 2, 1, 2]. We can choose serverA and serverB as primary servers, and serverC and serverD as their respective backup. The conditions hold true since memory[serverC] ≥ memory[serverA] and memory[serverD] ≥ memory[serverB]. Hence, the maximum system memory capacity is 3.

Example 2

Input:

memory = [1, 2, 1]

Output:

1

Explanation: Here, we have 3 servers [serverA, serverB, serverC] having memory sizes as [1, 2, 1]. We can choose serverA as a primary server, and serverB as its respective backup server. The conditions hold true since memory[serverB] ≥ memory[serverA]. Hence, the maximum system memory capacity is 1.

Example 3

Input:

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

Output:

5

Explanation: n the second configuration, the system memory capacity is memory[serverA] + memory[serverD] = 3. While in the third configuration, it is memory[serverA] + memory[serverC] = 5. Hence, the maximum system memory capacity is 5.

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

Amazon Games has introduced an exciting new game that revolves around dominoes! The game consists of n dominoes, each having a distinct size represented by an array tiles. In this game, the "order" of the dominoes is defined as the length of the longest strictly increasing subsequence (LIS) formed by their sizes. Additionally, there is another array removalOrder, which contains integers ranging from 0 to n-1. These integers indicate the positions of dominoes that can be removed one by one in the specified sequence. Your objective is to determine the maximum number of removals that can be performed while ensuring that the order (LIS) of the remaining dominoes remains at least a given threshold minOrder. Parameters - int tiles[n] – an array of n integers representing the sizes of dominoes. int removalOrder[n] – an array specifying the sequence in which the dominoes should be removed. int minOrder – an integer representing the minimum required LIS that must be maintained after removals. Return - The function should return a single integer, which represents the maximum number of removals possible while keeping the longest strictly increasing subsequence at least minOrder.

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

A lender lent money to a borrower, each day a different lender lent the money to the borrower. The borrower borrowed money on the jth day should payback on the (j+1)th day to maintain good credit and avoid defaulting. The borrower can payback the jth day loan from the (j+1)th day's borrowed money and can use the leftover money on that day. Find the maximum number of days the borrower can survive before defaulting. lender[i] represents the ith lending amount, and payback[i] represents the ith payback amount. Function Description Complete the function maximumNumberOfDaysToSurvive in the editor. maximumNumberOfDaysToSurvive has the following parameters:

  • int[] lender: an array of integers representing the lending amounts
  • int[] payback: an array of integers representing the payback amounts Returns int: the maximum number of days the borrower can survive before defaulting

Example 1

Input:

lender = [4, 6, 1, 8]
payback = [7, 10, 3, 9]

Output:

3

Explanation:

  1. Choose lender -> 1, so payback is 3.
  2. Choose lender -> 4, repay previous payback 3, hence remaining 4-3 = 1 (borrower spends it), the current Payback is 7.
  3. Choose lender -> 8, repay previous payback 7, hence remaining 8-7 = 1 (borrower spends it), the current Payback is 9.
  4. Left with lender -> 6, cannot repay previous payback which is 9, 9 > 6 hence default. So the borrower can survive 3 days.

Example 2

Input:

lender = [2, 1, 5]
payback = [2, 2, 5]

Output:

3

Explanation: The borrower can pay back each day's loan with the next day's borrowed money without any leftover, thus surviving for all 3 days.

Example 3

Input:

lender = [1, 1, 1, 2]
payback = [2, 2, 2, 3]

Output:

2

Explanation:

  1. Choose lender -> 1, so payback is 2.
  2. Choose lender -> 1, repay previous payback 2, hence no remaining (borrower spends it), the current Payback is 2.
  3. Left with lender -> 1, cannot repay previous payback which is 2, 2 > 1 hence default. So the borrower can survive 2 days.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You have an array of products, where each element contains how much product you have products = [2, 9, 4, 7, 5, 3]. Pick a subarray of products. Starting from the beginning of the subarray, pick some number of products. One restriction: the number of products you pick have to be strictly increasing. For example, you choose [7, 5, 3], you pick 4 products out of 7, 5 out of 5, there's nothing to pick from [3]. But you can pick [1, 2, 3], a total of 6 products. The ask is to find the maximum number of products you can pick. The answer for the above example is 16. Because you pick [2, 9, 4, 7] subarray and [2, 3, 4, 7] products out of it. Constraints

  • 1 **Function Description** Complete the function maximumProductsPickedin the editor.maximumProductsPicked` has the following parameter:
  • int[] products: an array of integers representing the stock of each product Returns int: the maximum number of products you can pick
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

HackerLand Sports Club wants to send a team for a relay race. There are n racers in the group indexed from 0 to n. The i^th racer has a speed of speed[i] units. The coach decided to send some contiguous subsegments of racers for the race i.e. racers with index i, i+1, i+2..., such that each racer has the same speed in the group to ensure smooth baton transfer. To achieve the goal, the coach decided to remove some racers from the group such that the number of racers with the same speed in some contiguous segment is maximum. Given the array, racers, and an integer k, find the maximum possible number of racers in some contiguous segment of racers with the same speed after at most k racers are removed. Function Description Complete the function maximumPossibleRacers in the editor. maximumPossibleRacers has the following parameters:

  • int[] speed: an array of integers representing the speed of each racer
  • int k: the maximum number of racers that can be removed Returns int: the maximum possible number of racers in some contiguous segment with the same speed after at most k racers are removed
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Amazon's AWS provides fast and efficient server solutions. The developers want to stress-test the quality of the servers' channels. They must ensure the following: Each of the packets must be sent via a single channel. Each of the channels must transfer at least one packet. The quality of the transfer for a channel is defined by the median of the sizes of all the data packets sent through that channel. Note: The median of an array is the middle element if the array is sorted in non-decreasing order. If the number of elements in the array is even, the median is the average of the two middle elements. Find the maximum possible sum of the qualities of all channels. If the answer is a floating-point value, round it to the next higher integer.

Constraints

  • 1 ≤ len(packets) ≤ 5×10⁵
  • 1 ≤ packets[i] ≤ 10⁹
  • 1 ≤ channels ≤ len(packets)

Example 1

Input:

packets = [1, 2, 3, 4, 5]
channels = 2

Output:

8

Explanation: At least one packet has to go through each of the 2 channels. One maximal solution is to transfer packets {1, 2, 3, 4) through channel 1 and packet {5} through channel 2. The quality of transfer for channel 1 is (2 + 3)/2 = 2.5 and that of channel 2 is 5. Their sum is 2.5 + 5 = 7.5 which rounds up to 8.

Example 2

Input:

packets = [2, 2, 1, 5, 3]
channels = 2

Output:

7

Explanation: One solution is to send packet {5} through one channel and {2, 2, 1, 3} through the other. The sum of quality is 5 + (2 + 2)/2 = 7

Example 3

Input:

packets = [89, 48, 14]
channels = 3

Output:

151

Explanation: There are 3 channels for 3 packets. Each channel carries one, so the overall sum of quality is 89 + 48 + 14 = 151

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

Amazon Engineering maintains a large number of logs of operations across all products. A software engineer is debugging an issue in a product. An efficient way to analyze logs is to write automated scripts to check for patterns. The engineer wants to find the maximum number of times a target word can be obtained by rearranging a subset of characters in a log entry. Given a log entry s and target word t, the target word can be obtained by selecting some subset of characters from s that can be rearranged to form string t and removing them from s. Determine the maximum number of times the target word can be removed from the given log entry. Note: Both strings s and t consist only of lowercase English letters. Function Description Complete the function maximumTimesWordRemoved in the editor. maximumTimesWordRemoved has the following parameters: String s: a log entry String t: a target word Returns int: the maximum number of times the target word can be removed

Constraints

Both string s and t consist only of lowercase English letters. (there might be some other constraints, will add once find out )

Example 1

Input:

s = "abacbc"
t = "bca"

Output:

2

Explanation: All characters were removed from s.

Example 2

Input:

s = "abdadccacd"
t = "edac"

Output:

0

Explanation: It is not possible to form the target word t from the characters in s.

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

In order to ensure a hassle-free user experience during the festive season, Amazon maintains logs of the days when its users use the Amazon Shopping app. The user traffic of a day is said to be the maximum number of users logged into the application during that day. If a user uses the application from day login[i] to day logout[i], it increases the traffic of each day from login[i] to logout[i] (both inclusive) by 1. That is, if login[i] = 4 and logout[i] = 6, then this user increases the traffic of days 4, 5 and 6 by 1. Given the login and logout day data of n users, find the number of days on which the user traffic is maximum. Note that all logins take place before all logouts on a single day. Function Description Complete the function maximumUserTraffic in the editor below. maximumUserTraffic has the following parameter(s):

  • int login[n]: an array of integers with login[i] denoting the login day of i^th user.
  • int logout[n]: an array of integers with logout[i] denoting the logout day of i^th user. Returns int: the number of days having maximum user traffic

Constraints

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

AMZ Interval Collection (A group of problems focused on operations involving intervals :) -

  1. Merge Intervals (Intern, NG)
  2. Find Overlapping Times (Intern)
  3. Get Maximum Sum Find Overlapping Times (Full-Time)
  4. Task Scheduler (Full-Time)
  5. Optimal Interval Difference Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

Constraints

  • 1 <

Example 1

Input:

intervals = [[1,3],[2,6],[8,10],[15,18]]

Output:

[[1,6],[8,10],[15,18]]

Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].

Example 2

Input:

intervals = [[1,4],[4,5]]

Output:

[[1,5]]

Explanation: Intervals [1,4] and [4,5] are considered overlapping.

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

Team of developers at Amazon is working on a feature that checks the strength of a password as it is set by a user. Analysts found that people use their personal information in passwords, which is insecure. The feature searches for the presence of a reference string as a subsequence of any permutation of the password. If any permutation contains the reference string as a subsequence, then the feature determines the minimum cost to remove characters from password so that no permutation contains the string reference as a subsequence. The removal of any character has a cost given in an array, cost, with 26 elements that represent the cost to replace 'a' (cost[0]) through 'z' (cost[25]). Given two strings password and reference, determine the minimum total cost to remove characters from password so that no permutation contains the string reference as a subsequence. Given the following: A string pwd, representing the password An array of 26 integers removalCosts, denoting the expense to remove each character A string target, the sequence that must not appear as a subsequence in any arrangement of pwd They want you to write a function that computes the minimum total cost necessary to modify the password by deleting characters, ensuring that no permutation of the altered password contains the target as a subsequence. Notes: A permutation is a sequence of integers from 1 to n of length n containing each number exactly once, for example, [1, 3, 2] is a permutation while [1, 2, 1] is not. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements, without changing the order of the remaining elements. For example, given the string "abcde", the following are subsequences: "a", "ace", "be", "bde" etc. while sequences like "dea", "abcde" are not subsequences.

Constraints

  • 1 ≤ |pwd| ≤ 10⁵
  • 1 ≤ |target| ≤ 10⁵
  • 0 ≤ removalCosts[i] ≤ 10° (this is confused, will modify once find reliable source) for i in range [0, 251 --> to be "251" or "25]" is a question; Will modify once find more reliable source :).
  • The strings pwd and target consist of lowercase English letters only.

Example 1

Input:

pwd = "abcdcbcb"
target = "bcb"
removalCosts = [2, 3, 1, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0,0,0,0]

Output:

3

Explanation: :)

Example 2

Input:

pwd = "kkkk"
target = "k"
removalCosts = [5,1,1,2,4,7,3,4,5,7,5,6,2,1,5,12,5,1,5,0,5,6,4,7,8,50]

Output:

20

Explanation: remove 5 occurances of k at a cost of 5*4 =20

Example 3

Input:

pwd = "adefgh"
target = "hf"
removalCosts = [1, 0, 0, 2, 4, 4, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Output:

1

Explanation:

Example 4

Input:

pwd = "abcdcbcb"
target = "bcb"
removalCosts = [2, 3, 1, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Output:

3

Explanation: The count of zeros differs between the two sources. The first source mentions 26 zeros, while the screenshot here shows 22 zeros. I'll go with the count from the official source. Different sources might have some discrepancies. Some we can verify, but others are hard to confirm. So, we’ll go with whatever is closest to the official data. If you know something more accurate, feel free to let us know — really appreciate it!

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

Amazon Delivery Centers dispatch parcels every day. There are n delivery centers, each having parcels[i] parcels to be delivered. On each day, an equal number of parcels are to be dispatched from each delivery center that has at least one parcel remaining. Find the minimum number of days needed to deliver all the parcels. Function Description Complete the function minDaysToDeliverParcels in the editor below. minDaysToDeliverParcels has the following parameters: int parcels[n]: the number of parcels at each center Returns int: the minimum number of days needed to deliver all the parcels Constraints

  • 1 ≤ n ≤ 10⁶
  • 0 ≤ parcels[i] ≤ 10⁹

Constraints

  • 1 ≤ n ≤ 10⁶
  • 0 ≤ parcels[i] ≤ 10⁹

Example 1

Input:

parcels = [2, 3, 4, 3, 3]

Output:

3

Explanation: All parcels can be delivered in a minimum of 3 days.

Example 2

Input:

parcels = [3, 3, 3, 3, 3, 3]

Output:

1

Explanation: Each delivery center can dispatch its 3 parcels on the first day.

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

Amazon is working on optimizing its delivery zones to ensure efficient and timely delivery of packages. Each delivery zone is represented as an interval indicating the range of house numbers it covers. The delivery zones can overlap. Given is a list of n delivery zones, where the i-th zone covers the interval (a(i), b(i) (inclusive)). Additionally, given is a maximum allowed length, k, for any new delivery zone that can be added. Your task is to add exactly one new delivery zone (a, b) such that the length of this new zone (b - a) is less than or equal to k. The goal is to minimize the number of disconnected delivery zones after adding the new delivery zone. A set of delivery zones [(a[1], b[1]), (a[2], b[2]), ..., (a[n], b[n])] is considered connected if every house number in the range (min(a[1], a[2],..., a[n]), max(b[1], b[2],..., b[n])) is covered by at least one delivery zones (a[i], b[i]) in the set. For example: [(1, 2), (2, 3), (1, 5)] is connected because every house number in the interval (min(1, 2, 1), max(2, 3, 5)) = (1, 5) is covered by a least one of the delivery zones. Note ~~ Not sure about the operator inbetween (min(1, 2, 1), max(2, 3, 5)) and (1, 5). Following is the original source image. If you know about it, feel free to lmk. I am more than happy to modyify it. Many thanks in advance! The set [(2, 2), (3, 4)] is not connected because the delivery zones (2, 2) and (3, 4) do not overlap each other and hence is disconnected.Amazon has something to say - The arrays 'a' and 'b' used above are considered to follow 1-based indexing! Function Description Write a function minimumSets. The function has the following parameters:

    1. List a: an array of integers representing the start of each delivery zone
    1. List b: an array of integers representing the end of each delivery zone
    1. k: the maximum allowed length for the new delivery zone Returns int: the minimum number of connected delivery zone groups after optimally inserting one new delivery zone of length ≤ k. The problem statement was modified on 05-27-2025 to align with the original problem source found by an old friend. Related source ss was included in the Problem Source section below.

Constraints

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

Example 1

Input:

a = [1, 2, 6, 7, 16]
b = [5, 4, 6, 14, 19]
k = 2

Output:

2

Explanation: The current delivery zones are: (1, 5), (2, 4), (6, 6), (7, 14), (16, 19) Add a new delivery zone (5, 7) (length = 2 ≤ k), which bridges the gap between (1, 5) and (6, 6), forming a larger connected component. Resulting components: Component 1: (1, 5), (2, 4), (5, 7), (6, 6), (7, 14) Component 2: (16, 19) Output: 2 However, if you add a new delivery zone (14, 16), you will end up with 3 connected sets: (1,5),(2.4),(5,7) (6,6) (7.14), (14, 16), (16, 19) Therefore, the optimal solution is to add the delivery zone (5, 7), resulting in the minimum number of connected sets, which is 2.

Example 2

Input:

a = [1, 2, 5, 10]
b = [2, 4, 8, 11]
k = 2

Output:

2

Explanation: Initial intervals: (1, 2), (2, 4), (5, 8), (10, 11) Add a new delivery zone (4, 5) into the array since 5 - 4 This test case was modified on 05-31-2025 to align with the original problem source found by an old friend. Endless thanks!

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

See the Image Source section for the original statement :) In a vast digital database, numbers were carefully stored as strings of binary characters—'0' and '1'. But something went wrong. In place of some digits, mysterious '!' marks appeared, casting doubt on what those digits should be. Should they be '0's or '1's? To make matters worse, whenever a '0' and '1' pair appeared together, they caused glitches—small errors that multiplied throughout the system. Some combinations triggered more glitches than others. The challenge now is to replace all the '!' marks in a way that minimizes the total glitches, while keeping the system stable and efficient.

Constraints

  • 1 ≤ errorString.length ≤ 10⁵
  • errorString[i] ∈ {'0', '1', '!'}
  • 1 ≤ x, y ≤ 10⁹

Example 1

Input:

errorString = "101!1"
x = 2
y = 3

Output:

9

Explanation: For example, given the string errorString = "101!1" with two different error costs: If the '!' is replaced with '0', the string becomes "10101". In this case, the sequence '01' appears multiple times, and so does the sequence '10'. The total number of errors is calculated based on how often these sequences appear and their associated error costs, resulting in a higher error count. If the '!' is replaced with '1', the string changes to "10111". While '01' still occurs several times, '10' appears far less frequently, leading to a lower total error count. Therefore, the goal is to choose the replacement that results in fewer errors. In this case, the option with the lowest error count is the better choice.

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

The manager of an Amazon warehouse needs to ship n products from different locations, the location of the ith product is represented by an array locations[i]. The manager is allowed to perform one operation at a time. Each operation is described below: If the inventory has two or more products, the manager can pick two products x and y from the inventory if they have different locations (locations[x]≠locations[y]) and ship both of them. If the inventory has one or more products, the manager can pick one product x from the inventory and ship it. Note: After shipping a product it gets removed from the inventory, and the rest of the products which are currently not shipped come together keeping the order the same as before. Given n products and an array locations, find the minimum number of operations that the manager has to perform to ship all of the products. Function Description Complete the function minOperation in the editor. minOperation has the following parameter(s): int locations[n]: the location of each product. Returns int: the minimum number of operations that the manager has to perform to ship all of the products.

Constraints

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

In an Amazon distribution center, a large number of parcels arrive daily, each assigned a distinct identifier ranging from 1 to n. The warehouse supervisor is tasked with organizing these parcels, but not by their identifiers. Instead, they need to follow a specific order provided by the sortingSequence, which is a permutation of the integers from 1 to n, ensuring the most efficient handling. Initially, no parcels have been organized (arrangedCount is 0). The supervisor checks the parcels from left to right. If a parcel's identifier matches the next one that needs to be organized (i.e., sortingSequence[i] == arrangedCount + 1), the supervisor arranges it and increments arrangedCount by one. If a parcel's identifier does not match the expected one in the permutation sequence, it is skipped. Your task is to determine how many complete checks (operations) the supervisor must perform to organize all the parcels. Each operation involves checking all parcels from the first to the last. Note: A sortingSequence is a valid permutation, meaning it is a sequence consisting of integers from 1 to n, each appearing exactly once. For example, [1, 3, 2] is a valid permutation, while [1, 2, 1] is not.

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

The manager of the Amazon warehouse has decided to make changes to the inventory by changing the prices of the products. Currently, the inventory has n products, where the price of the i-th product is represented by the array element prices[i]. The manager is given two integers: k - which is the maximum amount by which a product's price can be adjusted (increased or decreased) in a single operation, and d - which represents the target price difference. The goal is to ensure that the difference between the highest and lowest prices in the inventory is strictly less than d. In order to make changes to the inventory, the manager can do the following operation any number of times: The manager selects two indices x, y (1 ≤ x, yn), and an integer p (1 ≤ pk). The manager increases the price of the product x by p. The manager decreases the price of the product y by p. Given n products, an array prices, and the two integers k and d, find the minimum number of operations that the manager has to perform such that the maximum difference between the prices of any two products from the array of products is strictly less than d. Function Description Complete the function minOperations in the editor. minOperations has the following parameters:

  • int prices[n]: an array of integers representing the prices of n products
  • int k: the maximum amount that a price can be increased or decreased by in one operation
  • int d: the target difference Returns int: the minimum number of operations required to ensure the condition is satisfied, i.e., the difference between the maximum and minimum prices of the array of products is strictly less than d.

Constraints

  • 1 ≤ n ≤ 10³
  • 1 ≤ prices[i] ≤ 10³
  • 1 ≤ k ≤ 10³
  • 1 ≤ d ≤ 10³

Example 1

Input:

prices = [1, 5, 9, 11]
k = 4
d = 2

Output:

3

Explanation: The manager needs to perform a total of 3 operations. It is not possible to achieve the required condition, where the difference between the highest and lowest prices is strictly less than d = 2, in fewer than 3 operations. Therefore, the result is 3.

Example 2

Input:

prices = [1, 4, 6]
k = 1
d = 2

Output:

2

Explanation: Here, we have 3 products with prices [1, 4, 6]. The manager can adjust prices with a maximum of k = 1 per operation, and the required maximum price difference is d = 2. Now the max difference is 4 - 3 = 1, which is strictly less than d = 2. Hence, the manager needs to perform 2 operations.

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

An Amazon Fulfillment Associate has a set of items that need to be packed into two boxes. Given an integer array of the item weights (arr) to be packed, divide the item weights into two subsets, A and B, for packing into the associated boxes, while respecting the following conditions: The intersection of A and B is null. The union of A and B is equal to the original array. The number of elements in subset A is minimal. The sum of A's weights is greater than the sum of B's weights. Return the subset A in increasing order where the sum of A's weights is greater than the sum of B's weights. If more than one subset A exists, return the one with the maximal total weight. Function Description Complete the function minimalHeaviestSetA in the editor below. minimalHeaviestSetA has the following parameter(s):

  • int arr[]: an integer array of the weights of each item in the set Returns int[]: an integer array with the values of subset A

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ arr[i] ≤ 10⁴ (where `0 ≤ i

Example 1

Input:

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

Output:

[4, 5]

Explanation: The subset of A that satisfies the conditions is [4, 5]:

  • A is minimal (size 2)
  • Sum(A) = (4 + 5) = 9 > Sum(B) = (1 + 2 + 2 + 3) = 8
  • The intersection of A and B is null and their union is equal to arr.
  • The subset A with the maximal sum is [4, 5].

Example 2

Input:

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

Output:

[5, 6]

Explanation: The subset of A that satisfies the conditions is [5, 6]:

  • A is minimal (size 2)
  • Sum(A) = (5 + 6) = 11 > Sum(B) = (1 + 2 + 4) = 7
  • Sum(A) = (4 + 6) = 10 > Sum(B) = (1 + 2 + 5) = 8
  • The intersection of A and B is null and their union is equal to arr.
  • The subset A with the maximal sum is [5, 6].

Example 3

Input:

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

Output:

[6, 7]

Explanation: The 2 subsets in arr that satisfy the conditions for A are [5, 7] and [6, 7]:

  • A is minimal (size 2)
  • Sum(A) = (5 + 7) = 12 > Sum(B) = (2 + 3 + 6) = 11
  • Sum(A) = (6 + 7) = 13 > Sum(B) = (2 + 3 + 5) = 10
  • The intersection of A and B is null and their union is equal to arr.
  • The subset A where the sum of its weight is maximal is [6, 7].
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given an array 5 4 0 3 3 1, take sum of absolute differences between adjacent pairs i.e |5-4|+|4-0|+|0-3|+|3-3|+|3-1| = 10 The task is to remove as many elements from the array such that the sum remains same.

Example 1

Input:

arr = [5, 4, 0, 3, 3, 1]

Output:

[5, 0, 3, 1]

Explanation: Original sum of absolute differences: |5-4|+|4-0|+|0-3|+|3-3|+|3-1| = 10. After removing elements to minimize the array while keeping the sum the same: Solution 1: [5, 4, 0, 3, 1] => Sum = 10 Solution 2: [5, 0, 3, 1] => Sum = 10 Solution 2 is the acceptable answer as it has the minimum number of elements.

Example 2

Input:

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

Output:

[6, 2]

Explanation: :) IMPORTANT NOTE — The expected output from the original source is [6, 4, 3, 2]. However, a pro from the server pointed out that [6, 2] would actually make more sense as the correct answer for that example.

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

Not entirely sure for NG or FT, so I label both. Will update find more reliable source! :P With Amazon's new innovative EffiBin Kit users can effortlessly optimize the arrangement of their storage bins. This kit is designed to minimize the overall effort needed for efficient organization. The process starts with an array of bins, and the objective is to reduce the total effort required. The effort is the sum of efforts needed for each bin. Formally, given an array effort of size n, utilizing the EffiBin Kit, users can perform operations on the array, in each operation, the user chooses two positions i and j, such that the effort of the bin at position i (effort[i]) is divisible by the effort of the bin at position j (effort[j]). When this condition is satisfied, the effort of bin i can be updated to equal the effort of bin j. This operation can be repeated as many times as possible, on different bins or positions. An integer x is divisible by another integer y if x can be divided by y exactly, with nothing left over, for example, 6 is divisible by 3, while 7 is not. Find the minimum total effort after applying some (possibly zero) number of operations.

Constraints

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

Example 1

Input:

effort = [3, 6, 2, 5, 25]

Output:

17

Explanation:

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

Given two arrays a[] and b[] of equal length n. The task is to pair each element of array a to an element in array b, such that sum S of absolute differences of all the pairs is minimum. Suppose, two elements a[i] and a[j] (i≠j) of a are paired with elements b[p] and b[q] of b respectively, then p should not be equal to q. Function Description Complete the function minimizeSumOfAbsoluteDifferences in the editor. minimizeSumOfAbsoluteDifferences has the following parameters: int a[n]: an array of integers int b[n]: an array of integers Returns int: the minimum sum of absolute differences

Constraints

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

Given a collection of n cards. The i-th card (1 ≤ i ≤ n) has a number Ai on its front and a number Bi on its back. At the start, all the cards are facing upwards. He wants to minimize the range of numbers (i.e. the difference between the maximum and minimum values) on the face-up side. He is allowed to flip a maximum of m cards. Flipping a card will transition Bi to the face up side and Ai to the back. Help him find the minimum possible range after using at most m flips. Input The first line of the input consists of 2 integers n and m. The next line contains n integers, i-th of which denotes Ai. The next line contains n integers, i-th of which denotes Bi. Output Output a single integer, the minimum possible range.

Constraints

  • 1 ≤ m ≤ n
  • 1 ≤ Ai, Bi ≤ 107

Example 1

Input:

n = 5
m = 2
A = [1, 2, 17, 16, 9]
B = [3, 4, 5, 6, 11]

Output:

8

Explanation: By flipping card 3 and 4, we get the face up numbers {1, 2, 5, 6, 9}. This makes range=9-1=8.

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

Note - Initially, I thought this problem might be a duplicate of an existing one, but I wasn't able to find it. If you happen to come across it as a duplicate, please let me know! Thank you so much in advance!! You are the best!! Basically, Amazon has its warehouses lined up in a circle, you can start from any warehouse move in either clockwise or anti-clockwise direction, the direction must remain the same throughout the remaining moves. Each warehouse stores some items. The goal is to collect excess items from some warehouses and deliver them to others need them, so that each warehouse stores the same number of items in the end (guaranteed). The distance between 2 adjacent warehouses is 1, and the cost of each product transfer is the distance the product is moved. Function Description Complete the function minimizeWarehouseTransferCost in the editor. minimizeWarehouseTransferCost has the following parameter:

  • int[] warehouses: an array of integers representing the number of items in each warehouse Returns long integer: the minimum cost to make all warehouses store the same number of items
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

An inventory array product contains only 0 and 1, where 0 represents variant A and 1 represents variant B. In one operation, choose a subarray of length k. The cost of that operation is the sum of the values inside the chosen subarray. Then choose one index inside that subarray whose value is 1 and change it to 0. Return the minimum total cost needed to convert every product to variant A. Function Description Complete the function minCostToConvertAllToVariantA in the editor below. minCostToConvertAllToVariantA has the following parameters:

  • int[] product: the product variants
  • int k: the fixed operation window length Returns int: the minimum total cost.

Constraints

  • product[i] is either 0 or 1
  • 1 ≤ k ≤ product.length
  • Each operation must change exactly one 1 inside the chosen window to 0.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Janet has N bags in a row. Each bag has a weight (Wi). Janet can collect bags from either the leftmost or rightmost position, but there are energy costs: The cost of collecting a bag is the bag's weight (Wi) multiplied by X (if collecting from the left) or Y (if collecting from the right). If you are collecting a bag consecutively from the same side twice in a row, then there is an additional cost of El (if collected from the left side consecutively) or Er (if collected from the right side consecutively). Find the strategy that minimizes the total energy cost Janet spends to collect all the bags and display the minimum cost Bob has to pay. Input Format The first line of input contains five space-separated integers: N (number of bags), X, Y, El, Er (energy costs) The second line of input contains N space-separated integers representing the weight of each bag (Wi). Output Format Display the minimum energy cost expenditure for Bob.

Constraints

:O

Example 1

Input:

weights = [42, 3, 99]
X = 4
Y = 4
El = 19
Er = 1

Output:

576

Explanation:

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

Amazon CodeCraft introduces you to an engaging problem-solving challenge. You are presented with two integer lists named as: initialList and finalList of length m and n respectively. The finalList contains unique integers, while the initialList may contain duplicates. You are allowed to perform the following operation any number of times (possibly zero):

  • Insert any positive integer at any position (including the start and the end of the list) in the initialList. Your task is to determine the minimum number of operations required to transform the initialList into a subsequence of the finalList. It can be proven that it is always possible to transform the initialList into a subsequence of the finalList. Note: A subsequence of an array is a sequence that can be derived from the array by deleting some or no elements, without changing the order of the remaining elements. For example, [2, 7, 4] is a subsequence of [4, 2, 3, 7, 2, 1, 41], while [2, 4, 2] is not. Function Description Complete the function minimumInsertions in the editor below. minimumInsertions has the following parameters:
  • int finalList[n] : the elements in the finalList
  • int initialList[m]: the elements in the initialList Returns int: Minimum operations required to make finalList a subsequence of the elements in the initialList.

Example 1

Input:

finalList = [5, 1, 3]
initialList = [9, 4, 2, 3, 4]

Output:

2

Explanation: We make the following insertions in the initialList:

  • Operation 1: Insert 5 such that initialList = [5, 9, 4, 2, 3, 4], so current common subsequence [5, 3].
  • Operation 2: Insert 1 such that initialList = [5, 9, 4, 1, 2, 3, 4], so current common subsequence [5, 1, 3]. Now, consider the subsequence formed from the elements at index (0, 3, 5) of the initialList, and make up the finalList, hence we require a minimum of 2 operations.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Developers want to merge two source-control branches into one unified branch while preserving the relative order of commits from each branch. Each branch is represented by a lowercase string. Each character represents a commit priority, where a lower alphabetical character has higher priority. A conflict occurs when, in the merged branch, a lower-priority commit appears before a higher-priority commit. In other words, for positions i < j in the merged string, there is a conflict when merged[i] > merged[j]. Return the minimum possible number of conflicts over all valid merges of primary and secondary. A valid merge must contain every character from both branches and preserve the original order within each input branch.

Constraints

  • 1 ≤ primary.length, secondary.length ≤ 1000
  • primary and secondary contain lowercase English letters only.

Example 1

Input:

primary = "zc"
secondary = "d"

Output:

2

Explanation: Valid merges include zcd, zdc, and dzc. Their conflict counts are 2, 3, and 2, so the minimum is 2.

Example 2

Input:

primary = "dae"
secondary = "add"

Output:

1

Explanation: One optimal merge is adddae. The only conflict is d appearing before a inside the original primary branch, which cannot be avoided.

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

Heads up ->> Based on the original post, the actual question was VERY similar to the current question but not EXACT the same You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros. In one operation you can choose any subarray from initial and increment each value by one. Return the minimum number of operations to form a target array from initial. The test cases are generated so that the answer fits in a 32-bit integer.

Constraints

  • 1 ≤ target.length ≤ 10⁵
  • 1 ≤ target[i] ≤ 10⁵

Example 1

Input:

target = [1,2,3,2,1]

Output:

3

Explanation: We need at least 3 operations to form the target array from the initial array.

  • [0,0,0,0,0] increment 1 from index 0 to 4 (inclusive).
  • [1,1,1,1,1] increment 1 from index 1 to 3 (inclusive).
  • [1,2,2,2,1] increment 1 at index 2.
  • [1,2,3,2,1] target array is formed.

Example 2

Input:

target = [3,1,1,2]

Output:

4

Explanation:

  • [0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2]

Example 3

Input:

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

Output:

7

Explanation:

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

A work queue workList must be processed in order by two handlers. Each value in workList is a work type from 1 through m. For work type t, the first time a handler processes that type, or whenever the handler's previous job was a different type, that handler pays longPrepTime[t]. If the handler's previous job was the same type, that handler pays shortPrepTime[t] instead. Each job must be assigned to exactly one of the two handlers, and jobs must be processed in the order they appear. Return the minimum total preparation time. Function Description Complete the function minPreparationTime in the editor below. minPreparationTime has the following parameters:

  • int[] workList: the ordered work types
  • int[] longPrepTime: long preparation time for each work type
  • int[] shortPrepTime: short preparation time for each work type Returns int: the minimum total preparation time.

Constraints

  • workList[i] identifies a work type between 1 and m
  • longPrepTime and shortPrepTime contain one entry per work type.
  • Jobs must be processed in order.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

An online marketplace has onboarded n merchants, each operating within a designated geographical range. The operating zone of merchant i is defined by the interval spanning from zoneStart[i] to zoneEnd[i]. A set of k merchants is termed cohesive (inclusive) if there exists at least one merchant whose operational territory overlaps with (or touches) all the other (k-1) merchants’ operational zones. The marketplace plans to relocate some merchants to new areas. Your goal is to determine the minimum number of merchants that need to be moved so that the remaining merchants form a cohesive subset. Function Description Complete the predefined function in the editor. minimumRetailers has the following parameters:

  • int zoneStart[n]: the left ends of the operating regions
  • int zoneEnd[n]: the right ends of the operating regions Returns int: the smallest number of merchants that need to be relocated Constraints
  • 1 ≤ n ≤ 10⁵
  • `1 ≤ zoneStart[i] ≤ zoneEnd[i] ≤ 10⁹ (1

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ regionStart[i] ≤ regionEnd[i] ≤ 10⁹ (1 ≤ i ≤ n)
  • There can be multiple regions with the same start and end points
  • Complete constraints was added on 05-14-2025. You can find relevant source image will be uploaded next time..

Example 1

Input:

zoneStart = [1, 3, 4, 6, 9]
zoneEnd = [2, 8, 5, 7, 10]

Output:

2

Explanation:

Example 2

Input:

zoneStart = [1, 2, 3, 4]
zoneEnd = [2, 3, 5, 5]

Output:

1

Explanation: Region 1 (1, 2) intersects only region 2. (move regions 3 and 4) Region 2 (2, 3) intersects regions 1 and 3. (move region 4) Region 3 (3, 5) intersects regions 2 and 4. (move region 1) Region 4 (4, 5) intersects region 3. (move regions 1 and 2) The minimum number of moves is 1, moving region 1 or 4

Example 3

Input:

zoneStart = [1, 2, 4]
zoneEnd = [7, 5, 6]

Output:

0

Explanation: Will update once find reliable resources. As always.

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

Note - Similar to LC 2214 In Amazon Prime Games, a player needs to pass n rounds sequentially. The rules are as follows: The player loses power[i] health to complete round i. The player's health must always be greater than 0 at all times. The player can use armor in only one round, which prevents damage of min(armor, power[i]) for that round. You need to determine the minimum starting health required for the player to win the game. Thank you so much, Spike!

Constraints

  • The first line contains an integer n (1 ≤ n ≤ 10⁵) — the number of rounds.
  • The next n lines contain integers power[i] (1 ≤ power[i] ≤ 10⁹) — the health cost to complete each round.
  • The last line contains an integer armor (1 ≤ armor ≤ 10⁹) — the maximum amount of health that may be returned by armor.

Example 1

Input:

power = [1, 2, 6, 7]
armor = 5

Output:

12

Explanation: Starting health = 12 Round 1: Health = 12 - 1 = 11 Round 2: Health = 11 - 2 = 9 Round 3: Health = 9 - (6 - 5) = 8 Round 4: Health = 8 - 7 = 1 The minimum starting health required to win the game is 12.

Example 2

Input:

power = [1, 2, 3]
armor = 1

Output:

6

Explanation: Starting health = 6 Round 1: Health = 6 - 1 + 1 (armor) = 6 Round 2: Health = 6 - 2 = 4 Round 3: Health = 4 - 3 = 1 The minimum starting health required to win the game is 6.

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

Need to efficiently distribute a collection of computer games among k different children. Each game is characterized by its size, denoted by gameSize[i] for 1 ≤ i ≤ n. To facilitate the distribution process, the coordinator opts to utilize pen drives, ordering k pen drives with identical storage capacities. Each child can receive a maximum of 2 games, and every child must receive at least one game, also no game should be left unassigned. Considering the impracticality of transferring large game files over the internet, the strategy involves determining the minimum storage capacity required for the pen drives. A pen drive can only store games if the sum of their sizes does not exceed the pen drive's storage capacity. What is the minimum storage capacity of pen drives that you must order to be able to give these games to the children? Function Description Complete the function findMinimumPenDriveCapacity in the editor. findMinimumPenDriveCapacity has the following parameters:

  • int[] gameSize: an array of integers representing the sizes of the games
  • int k: the number of children Returns int: the minimum storage capacity of pen drives required
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Within the Amazon Gaming Distribution System, a logistics coordinator is faced with the task of efficiently distributing a collection of n computer games among k different children. Each game is characterized by its size, denoted by gameSize[i] for 1 ≤ i ≤ n. To facilitate the distribution process, the coordinator opts to utilize pen drives, ordering k pen drives with identical storage capacities. Each child can receive a maximum of 2 games, and every child must receive at least one game, also no game should be left unassigned. Considering the impracticality of transferring large game files over the internet, the strategy involves determining the minimum storage capacity required for the pen drives. A pen drive can only store games if the sum of their sizes does not exceed the pen drive's storage capacity. What is the minimum storage capacity of pen drives that you must order to be able to give these games to the children?

Example 1

Input:

gameSize = [9, 2, 4, 6]
k = 3

Output:

9

Explanation: We note that we will need pen drives of the size of at least 9 units, to store the first game. This also turns out to be the minimum size of pen drives that should be ordered to give the games to these children. We can use the first pen drive to store the game of size 9, the 2nd one to store the second and third games, and the 3rd pen drive to store the fourth game. Hence, the minimum capacity of pen drives required is 9 units.

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

Example output is a p

Example 1

Input:

s = "0100101"

Output:

1

Explanation: Output is just a placeholder. Lets ignore it for now..

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

Amazon operates multiple fulfillment centers. Each center follows a special packaging rule. You are given: An integer list packEffort of size m where packEffort[i] is the packaging effort required for the i-th item. An integer list packageCount of size n where packageCount[i] indicates that at the i-th fulfillment center, if you pay to package at least packageCount[i] items, you get 2 extra items for free. The 2 bonus (free) items must each have a packaging effort less than or equal to the smallest effort among the paid items at that center. You can use any fulfillment center once or not at all. Goal: Return the minimum total packaging effort required to package all m items using any number of fulfillment centers. Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ m ≤ 10⁵
  • 0 ≤ packEffort[i] ≤ 10⁴
  • Each item must be packaged exactly once A super huge thank you to an incredible friend who so generously shared the valuable source!
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given a string consisting of '0', '1', and '!', where '!' represents a character that can be replaced with either '0' or '1'. Additionally, you are given two integers x and y. Your task is to replace all '!' characters in such a way that you minimize the calculated value based on the following rules: For every adjacent pair of characters: If the pair is '01', the contribution to the total is x. If the pair is '10', the contribution to the total is y. Function Description Complete the function calculateMinimumValue in the editor. calculateMinimumValue has the following parameters:

    1. String s: a binary string containing '0', '1', and '!' characters
    1. int x: the contribution value for '01' pairs
    1. int y: the contribution value for '10' pairs Returns int: the minimum calculated value after replacing all '!' characters

Constraints

  • The string contains at least one '!', and its length is between 1 and ( 10⁵ )
  • ( x ) and ( y ) are non-negative integers

Example 1

Input:

s = "01!0"
x = 2
y = 3

Output:

8

Explanation: Replace '!' with '0' to get '0100': Pairs: ('01', '10') → Contribution: ( 2 imes 1 + 2 imes 3 = 8 ) Replace '!' with '1' to get '0110': Pairs: ('01', '10') → Contribution: ( 2 imes 2 + 2 imes 3 = 10 ) The minimum contribution is ( 8 ).

Example 2

Input:

s = "!0!1"
x = 3
y = 4

Output:

7

Explanation: Replace the first '!' with '1' and the second '!' with '0' to get '10' and '01': Pairs: ('10', '01') → Contribution: ( 3 + 4 = 7 )

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

A company will launch a series of marketing campaigns over several weeks. Each campaign has a certain cost. They want to launch at least one campaign every week, and to plan the campaigns in a way that minimizes the total weekly input. The weekly input is the maximum cost of any campaign planned in that week. Given the cost of the campaigns in a list, costs, and the number of weeks, find the minimum sum of weekly inputs that can be achieved with optimal planning. The campaigns must be organized in the same order in which they appear in the list costs. Function Description Complete the function minimumWeeklyInput in the editor below. minimumWeeklyInput has the following parameters:

  • int costs[n]: the order and cost of the campaigns
  • int weeks: the number of weeks to organize all the campaigns Returns int: the minimum possible overall weekly input

Constraints

  • 1 ≤ n ≤ 300
  • 1 ≤ weeks ≤ n ≤ 300
  • 1 ≤ costs[i] ≤ 10⁵

Example 1

Input:

costs = [1000, 500, 2000, 8000, 1500]
weeks = 3

Output:

9500

Explanation: The company can organize the first campaign in the first week, the second campaign in the second week, and the remaining campaigns in the third week. The sum of weekly inputs in this planning is 1000 + 500 + max(2000, 8000, 1500) = 9500, which is the minimum possible input. Return 9500.

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

You are given a list of transactions, where each transaction is a list of products purchased together. Return the pair of products that appears most frequently across all transactions. Rules: A pair consists of exactly two distinct products. (A, B) and (B, A) are considered the same pair — always return it in lexicographic order. If multiple pairs have the same highest frequency, return the lexicographically smallest pair. Duplicate items within a transaction should be counted only once. Each transaction can contribute multiple pairs.

Constraints

1 ≤ transactions.length ≤ 10³ 1 ≤ transactions[i].length ≤ 100 Each product name is a non-empty string of uppercase letters.

Example 1

Input:

transactions = [["A","B"],["A","B"],["A","C"]]

Output:

["A","B"]

Explanation: Pairs across all transactions: AB appears in transaction 1 and 2 (count=2), AC appears in transaction 3 (count=1). Most frequent pair is (A, B). Return ["A","B"].

Example 2

Input:

transactions = [["A","B","C"],["A","B"],["B","C"],["A","C"]]

Output:

["A","B"]

Explanation: Transaction 1 contributes pairs AB, AC, BC. Transactions 2–4 contribute AB, BC, AC respectively. Counts: AB=2, AC=2, BC=2 — all tied. Return the lexicographically smallest pair: ["A","B"].

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

Given a string s consisting of lowercase letters, return the lexicographically smallest "perfect" string strictly greater than s of the same length (a perfect string has no adjacent equal characters and no palindromic substring of length ≥ 2). If no such string exists, return "-1".

Example 1

Input:

s = "abzzzcd"

Output:

"acababa"

Explanation: :)

Example 2

Input:

s = "zzab"

Output:

"-1"

Explanation: Because there will be no perfect lexigraphically greater string than zzab.

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

You are given a list of products, where each product has a name, price, and weight. Your task is to determine how many duplicate products are in the list. A duplicate product is defined as a product that has the same name, price, and weight as another product in the list. Function Signature public static int numDuplicates(List name, List price, List weight) Parameters:

  • List name: A list of strings where name[i] represents the name of the product at index i.
  • List price: A list of integers where price[i] represents the price of the product at index i.
  • List weight: A list of integers where weight[i] represents the weight of the product at index i. Returns: An integer denoting the number of duplicate products in the list. Constraints
  • 1 ≤ n ≤ 10⁵
  • 1 ≤ price[i], weight[i] ≤ 1000
  • name[i] consists of lowercase English letters (a-z) and has at most 10 characters.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

The Banana Company employs small, autonomous transport units, known as "Bananaer", to efficiently carry large stacks of products within its warehouses. These Bananaer navigate along predefined paths in a warehouse, which can be represented as a Cartesian plane. Each Bananaer is stationed at distinct integral coordinate points of the form (x, y). When a product needs to be delivered to a specific location (i, j), the system selects the nearest available Bananaer to complete the task. However, some Bananaers may seldom be chosen due to being surrounded by other units. A Bananaer is considered idle if it has another Bananaer positioned directly above, below, to the left, and to the right of it. This means it is entirely enclosed and less likely to be selected for work. It is guaranteed that no two Bananaers share the same coordinates. Given the locations of n Bananaers on the Cartesian plane, determine how many Bananers are idle based on the above criteria.

Constraints

  • 1 ≤ n ≤ 10⁵
  • -10⁹ ≤ x[i], y[i] ≤ 10⁹

Example 1

Input:

x = [0, 0, 0, 0, 0, 1, 1, 1, 2, -1, -1, -2, -1]
y = [-1, 0, 1, 2, -2, 0, 1, -1, 0, 1, -1, 0, 0]

Output:

5

Explanation: The cartesian plane with idle robots marked red can be represented as: The robots at locations (0, 0), (1, 0), (-1, -0), (0, 1), and (0, -1) are idle as they are surrounded by robots on all 4 sides.

Example 2

Input:

x = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3]
y = [1, 2, 3, 1, 2, 3, 5, 1, 2, 3]

Output:

2

Explanation: The 10 robots are arranged as follows:

  • The robot at (2, 2) is idle because it has robots at (1, 2), (3, 2), (2, 3), and (2, 1) directly to the left, right, up, and down respectively.
  • The robot at (2, 3) is idle because it has robots at (1, 3), (3, 3), (2, 5), and (2, 2) directly to the left, right, up, and down respectively. There are 2 idle robots in this arrangement.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Feel free to see the Image Source section at the very bottom of the page for the original problem statement Amazon, with its vast network of delivery centers scattered across the globe, operates on a massive number line stretching from -10⁹ to 10⁹. Imagine each center as a beacon along this number line, positioned at specific points known as center[i]. Now, Amazon is on a mission to find perfect warehouse spots, places where products from every delivery center can be gathered without exceeding a maximum travel distance, d. These warehouse spots, or "suitable locations," must be within reach of all delivery centers, ensuring that the total travel distance for bringing products to any one point doesn’t go beyond d. The task is to figure out how many such ideal locations exist on the number line, where the journey for all products is within this limit. Can't thank engouth to the legendary GG of Error-Free Excellence - spike !

Constraints

  • 1 ≤ n ≤ 10⁵
  • -10⁹ ≤ center[i] ≤ 109
  • 0 ≤ d ≤ 10¹⁵

Example 1

Input:

center = [-2, 1, 0]
d = 8

Output:

3

Explanation: ->> Check out the Image Source section at the bottom of the page for the original explanation Let’s imagine setting up the warehouse at x = -3. First, we bring products from the closest delivery center at center[0] = -2. The distance to bring the products to x = -3 is |-3 - (-2)| = 1, and then we return, covering another 1. Next, we move on to the products from centers 1 and 2, bringing them to x = -3. The total travel distance ends up being 1 + 1 + 4 + 4 + 3 + 3 = 16. Since this exceeds the maximum distance, d, this spot is not suitable for the warehouse. Now, let’s try placing the warehouse at x = 0. The distance to bring products from center[0] = -2 is 2 * |0 - (-2)|, and from center[1] = 1, it’s 2 * |0 - 1|. Finally, the products from center[2] = 0 are already there, so the distance is 2 * |0 - 0|. Adding it all up, we get a total travel distance of 6, which is within the limit of d. So, x = 0 is a suitable location for the warehouse! Let’s try placing the warehouse at x = -1 this time. To bring the products from center[0] = -2, the travel distance is 2 * |-1 - (-2)|. For center[1] = 1, it’s 2 * |-1 - 1|, and for center[2] = 0, the distance is 2 * |-1 - 0|. Adding everything together, the total distance is 8, which is within the limit of d. This makes x = -1 another suitable location for the warehouse! Now, let's consider placing the warehouse at x = 1. To bring products from center[0] = -2, the travel distance is 2 * |1 - (-2)|. For center[1] = 1, the distance is 2 * |1 - 1|, and from center[2] = 0, it’s 2 * |1 - 0|. When we add it all up, the total distance traveled is 8, which is within the limit of d. So, x = 1 is also a suitable location for the warehouse! The only suitable locations for the warehouse are x = -1, x = 0, and x = 1. Since there are 3 such spots, the total count of suitable locations is 3.

Example 2

Input:

center = [2, 0, 3, -4]
d = 22

Output:

5

Explanation: ->> Check out the Image Source section at the bottom of the page for the original explanation

Example 3

Input:

center = [-3, 2, 2]
d = 8

Output:

0

Explanation: ->> Check out the Image Source section at the bottom of the page for the original explanation

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

Amazon aims to review its network of m servers deployed across different regions globally. The workloads on these servers are stored in the array workloads. A collection of servers is labeled as performing optimally when the difference between the highest and lowest workloads in that collection equals difference. A collection is termed a consecutive group if there are two positions x and y such that 1 ≤ x ≤ y ≤ m, where all servers from position x to y are included in the group, with none from outside. A group of servers is called contiguous servers when there exists x, y such that 1 ≤ x ≤ y ≤ m and all the servers between i and j are in the group and no other should be in the group. Given the integer array workloads and integer difference, determine how many consecutive groups of servers meet the optimal performance criteria.

Example 1

Input:

load = [2, 4, 6]
k = 2

Output:

2

Explanation: We return 2 based on the part highlighted in orange.

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

AMZ Interval Collection (A group of problems focused on operations involving intervals :) -

  1. Optimal Interval Difference
  2. Merge Intervals (Intern, NG)
  3. Find Overlapping Times (Intern)
  4. Get Maximum Sum Find Overlapping Times (Full-Time)
  5. Task Scheduler (Full-Time) Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. In the Optimal Interval Difference problem, you are given an array of intervals, where each interval is represented as [start[i], end[i]]. Your task is to find the minimum difference between the start and end points of the common overlapping intervals. That is from the set of intervals obtained after merging the overlapping intervals, compute the difference between the start [i-1] and end[i] points for each interval after sorting and return the minimum of those differences. For example, if intervals are (1,5), (7,9) and (2,4), then after merging the intervals we get (1,5) and (7,9). And the minimum difference between them is 7-5=2. Input Format The first line of input contains an integer N, denoting the number of intervals. The next N lines contain two space-separated integers each, representing the start and end points of the intervals. Output Format Print a single integer representing the minimum difference between the start and end points of the common overlapping intervals.

Example 1

Input:

intervals = [[1, 4], [2, 5], [8, 11]]

Output:

3

Explanation:

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

You are given a device with a limited amount of memory. Each device must run two applications at the same time: one foreground application and one background application. Each application is identified by a unique integer ID (unique within its type), requires a fixed non-zero amount of memory to execute, and is classified as either foreground or background. A pair of applications (one foreground and one background) is considered optimal if: Their combined memory usage is less than or equal to the device's capacity. There is no other valid pair with a higher combined memory usage without exceeding the device's capacity. Your task is to write an algorithm that finds all pairs of foreground and background applications that optimally utilize the device memory. The function should return a list of pairs [foregroundAppID, backgroundAppID] representing the IDs of applications that optimally utilize the device. If no valid pair exists, return a list with an empty pair. Input Format An integer deviceCapacity representing the device's memory. A list of pairs for foreground applications. A list of pairs for background applications. Output Format A list of pairs of integers [foregroundAppID, backgroundAppID] for each optimal application pair. If no valid pair exists, return a list containing an empty pair.

Example 1

Input:

deviceCapacity = 7
foregroundAppList = [[1, 2], [2, 4], [3, 6]]
backgroundAppList = [[1, 2]]

Output:

[[2, 1]]

Explanation: The possible pairs are: [1, 1] uses 2 + 2 = 4 memory. [2, 1] uses 4 + 2 = 6 memory. [3, 1] uses 6 + 2 = 8 memory (exceeds the device capacity). Since 6 is the largest usage within capacity, [2, 1] is the only optimal pair.

Example 2

Input:

deviceCapacity = 10
foregroundAppList = [[1, 3], [2, 5], [3, 7], [4, 10]]
backgroundAppList = [[1, 2], [2, 3], [3, 4], [4, 5]]

Output:

[[2, 4], [3, 2]]

Explanation: There are two optimal pairs: Pair [2, 4]: Foreground app 2 uses 5 memory, background app 4 uses 5 memory; combined = 10. Pair [3, 2]: Foreground app 3 uses 7 memory, background app 2 uses 3 memory; combined = 10.

Example 3

Input:

deviceCapacity = 16
foregroundAppList = [[2, 7], [3, 14]]
backgroundAppList = [[2, 10], [3, 14]]

Output:

[[]]

Explanation: No combination of one foreground and one background application fits within the device capacity. Hence, the output is a list with an empty pair.

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

In an Amazon inventory management, an operations analyst is dealing with a set of initial product identifiers represented by strings. The type of a product identifier is determined by the first and last letters in the identifier string, for example, the type of the identifier string "abddac" is "ac". The analyst wants to optimize the product identifiers by performing a series of operations on the string to maximize the number of operations between the final and initial types. Given a product identifier string s, the analyst can perform one operation at a time, involving the removal of either the first or last letter from the string. Find the maximum number of operations they can perform on the string while ensuring that its type aligns with the initial string's type. Note: The type of an empty string is "", and the type of a string with a single character, like "a", is "aa". Function Description Complete the function optimizeIdentifiers in the editor. optimizeIdentifiers has the following parameter:

  • string s: the initial product identifiers. Returns int: the maximum number of operations the operations analyst can perform on the string, such that its type is equal to the initial string's type.

Constraints

  • 2 ≤ |s| ≤ 2 * 10⁵
  • String s consists of lowercase English letters only.

Example 1

Input:

s = "babdcaac"

Output:

5

Explanation: The type of the initial string is "bc". The only valid final strings (strings with a type equal to the type of the initial string "bc") are "babdcaac", "bdc", and "babdc" with a total of operations performed of 0, 5, and 3 respectively, hence the answer is 5.

Example 2

Input:

s = "hchc"

Output:

2

Explanation: The type of the initial string is "hc", so the operations analyst can remove the first 2 or last 2 letters and get the string "hc" with a type "hc", hence the answer is 2.

Example 3

Input:

s = "abbc"

Output:

0

Explanation: The operations analyst can't remove any letters from the string since the type will change, hence the answer is 0.

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

In an Amazon inventory management, an operations analyst is dealing with a set of initial product identifiers represented by strings. The type of a string product identifier is determined by the first and last letters in the identifier string, for example, the type of the identifier string "abddaac" is "ac". The analyst wants to optimize the product identifiers by performing a series of operations on the string to maximize the number of operation between the final and initial types. Given a product identifier string s, the analyst can perform one operation at a time, involving the removal of either the first or last letter from the string. Find the maximum number of operations they can perform on the string while ensuring that its type aligns with the initial string's type. Note: The type of an empty string" is", and the type of a string with a single character, like "a", is "aa". Function Description Complete the function optimizedIdentifiers in the editor below. optimizedIdentifiers has the following parameter:

    1. string s: the initial product identifiers. Returns int: the maximum number of operations the operations analyst can perform on the string, such that its type is equal to the initial string's type.

Constraints

  • 2 ≤ |s| ≤ 2 * 10⁵
  • String s consists of lowercase English letters only.

Example 1

Input:

s = "hchc"

Output:

2

Explanation: The type of the initial string is "h", so the operations analyst can remove the first 2 or last 2 letters and get the string "h" with a type "h", hence the answer is 2.

Example 2

Input:

s = "abbc"

Output:

0

Explanation: The operations analyst can't remove any letters from the string since the type will change, hence the answer is 0.

Example 3

Input:

s = "babdcaac"

Output:

0

Explanation: The type of the initial string s is "bc": Final String, Number of Operations, Type babdcaac, 0, bc bdcaac, 6, bc d, 7, dd bdc, 5, bc babdc, 3, bc From the above final strings, the only valid final strings (strings with a type equal to the type of the initial string "bc") are "babdcaac", "bdc", and "babdc" with a total of operations performed of 0, 5, and 3 respectively, hence the answer is 5.

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

Note - Feel free to checkout the source image for the original statement :) A barcode scanner's settings are stored in a backend system as a single string of configurations, each encoded with a four-digit ordinal index followed by a configuration value, all separated by '|'. To set up the scanner correctly, the client needs to request this string and present the configurations in the proper sequence. Your task is to ensure the validity of this configuration string and return the configurations in the right order. The validation criteria include ensuring that configurations are separated by '|', indices are sequential and unique without any gaps, configuration values are alphanumeric and unique, and there are no duplicate ordinal indices. If the string fails these checks, the function should return ["Invalid configuration"].

Constraints

  • 1 ≤ orders ≤ 9999
  • 1 ≤ orders(configuration) ≤ 9999
  • Order values may not be unique or complete
  • Configuration values are not always unique, the same configuration may appear in multiple configuration steps

Example 1

Input:

layout = "0001LAJ5KBX9H8|0003UKURNK403F|0002MO6K1Z9WFA|0004OWRXZFMS2C"

Output:

["LAJ5KBX9H8", "MO6K1Z9WFA", "UKURNK403F", "OWRXZFMS2C"]

Explanation: The configuration string contains several values, each prefixed with a four-digit order number. For instance, "LAJ5KBX9H8" with the prefix "0001" is listed first, while "MO6K1Z9WFA" is marked with "0002" and therefore comes second. Even though "UKURNK403F" appears second in the string, its prefix "0003" places it third in the final sequence. Lastly, "OWRXZFMS2C" has the prefix "0004" and is listed fourth.

Example 2

Input:

layout = "000533B8XLD2EZ|0001DJ2M2JBZZR|0002Y9YK0A7MYO|0004IKDJCAPG5Q|0003IBHMH59SBO"

Output:

["DJ2M2JBZZR", "Y9YK0A7MYO", "IBHMH59SBO", "IKDJCAPG5Q", "33B8XLD2EZ"]

Explanation: No explanation for now

Example 3

Input:

layout = "0002f7c22e7904|000176a3a4d214|000305d29f4a4b"

Output:

["76a3a4d214", "f7c22e7904", "05d29f4a4b"]

Explanation: No explanation for now :)

Example 4

Input:

layout = "0002f7c22e7904|000176a3a4d214|000205d29f4a4b"

Output:

["Invalid configuration"]

Explanation: ..

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

An amazon fulfillment associate has a set of items that need to be packed in two boxes, given an array of item weights (arr) to be placed, divide the item weights subsets A and B for packing into associate boxes while respecting the following conditions. The conditions: The intersection of A and B is null. The union of A and B equals the original array. Subset A must be minimal in size. The sum of A's weights is greater than the sum of B's weights. Function Description Complete the function packItems in the editor. packItems has the following parameter:

  • int[] arr: an array of integers representing item weights Returns int[]: an array of integers representing the weights of items in subset A

Example 1

Input:

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

Output:

[6, 7]

Explanation: Subset A = [6, 7] and Subset B = [3, 5, 2]. The intersection of A and B is null, the union equals the original array, A is minimal in size, and the sum of A's weights (13) is greater than the sum of B's weights (10).

Example 2

Input:

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

Output:

[4, 5]

Explanation: Subset A = [4, 5] and Subset B = [2, 3, 1, 2]. The intersection of A and B is null, the union equals the original array, A is minimal in size, and the sum of A's weights (9) is greater than the sum of B's weights (8).

Example 3

Input:

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

Output:

[1, 3, 4]

Explanation:

Example 4

Input:

arr = [2, 2, 2, 3]

Output:

[2, 2, 2]

Explanation:

Example 5

Input:

arr = [1,1,1,1,4,4,4,7,8]

Output:

[4,4,4,8]

Explanation:

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

Each shipment scenario has a list of truck capacities and a list of pa

Constraints

The number of scenarios and the lengths of the nested arrays can be large, so the solution should avoid brute-force backtracking over all assignments.

Example 1

Input:

truckCapacities = [[7]]
packageWeights = [[4, 3]]

Output:

[1]

Explanation: The single truck delivers package 4, its capacity drops to 3, and it can still deliver package 3. The scenario is feasible.

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

Sup! I might be a sister question of Password Strength Your group at Amazon has recently set up a fresh verification rule for internal employee login credentials. A credential consists solely of lowercase English alphabets and is deemed acceptable only if it includes at least one vowel and at least one consonant. The vowel set includes 'a', 'e', 'i', 'o', 'u'. All other letters are treated as consonants. Given a text string representing the credential, determine and return its strength value. If the entire credential fails to meet the criteria, return 0. Note: A piece refers to a sequence of neighboring characters taken from the original string, maintaining the same order.

Constraints

  • 1 ≤ |credential| ≤ 10 (the length of credential)
  • Credential consists of lowercase English letters only.

Example 1

Input:

credential = "hackerrank"

Output:

3

Explanation: This credential can be broken down into three consecutive sections: "hack", "er", and "rank". Every section includes at least one vowel and one consonant. It can be verified that the string cannot be split into more than three valid sections. Therefore, the strength value of the credential is 3.

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

Amazon ships millions of packages every day. A large percentage of them are fulfilled by Amazon, so it is important to minimize shipping costs. It has been found that moving a group of 3 packages to the shipping facility together is most efficient. The shipping process needs to be optimized at a new warehouse. There are the following types of queries or requests: INSERT package id: insert package id in the queue of packages to be shipped SHIP -: ship the group of 3 items that were in the queue earliest i.e. they are returned in the order they entered Perform q queries and return a list of lists, one for every SHIP - type query. The lists are either; 3 package ID strings in the order they were queued. Or, if there are not enough packages in the queue to fulfill the query, the result is I"N/A"J. Note: Initially, the queue is empty. The list of packages shipped per group should be in the order they were queued. The function performQueries take List<List<>> of type String as a parameter which contains each query where - --> list.get(i).get(0) = INSERT | SHIP --> list.get(i).get(1) = shipmentID | - Returns List>: a list of lists, one for every SHIP - type query

Example 1

Input:

queries = [["INSERT", "GT23513413"], ["INSERT", "TQC2451340"], ["SHIP", "-"], ["INSERT", "VYP8561991"], ["SHIP", "-"]]

Output:

[["N/ A"], ["GT23513413", "TQC2451340", "VYP8561991"]]

Explanation: :)

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

In this stock price prediction game launched on Amazon Games, Player 1 provides Player 2 with stock market data for n consecutive days, representing Amazon's stock prices on each day, represented by stockData[]. The rules of the game are as follows:

  1. Player 1 will tell Player 2 a specific day number i (where 1 ≤ i ≤ n)
  2. Player 2 has to find the nearest day j (1 3. If there are more than one j which satisfies Rule 2, then Player 2 will find the day number which is smaller. (i.e. the smallest j satisfying Rule 2)
  3. If no such day j exists, then answer for that case is -1 Given q queries in the array queries, the task is to find the answer for each queries[i] in the queries and return a list of answer as per the above rules corresponding to each query. Note: The description and the answer format both adhere to 1-based indexing for the arrays. (Please see the below Example for better understanding :) Function Description Complete the function predictAnswer in the editor. predictAnswer has 2 parameters:
  • int stockData[n]: an integer array denoting the value of each stockData[i] is the stock price on the i-th day (where 0 ≤ i **Returns** int[]: an integer array denoting the value at each index iis the answer toqueries[i]`

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ stockData[i] ≤ 10⁹
  • 1 ≤ q ≤ 10⁵
  • 1 ≤ queries[j] ≤ n

Example 1

Input:

stockData = [5, 6, 8, 4, 9, 10, 8, 3, 6, 4]
queries = [6, 5, 4]

Output:

[5, 4, 8]

Explanation: On day 6, the stock price is 10. Both 9 and 8 are lower prices one day away. Choose 9 (day 5) because it is before day 6. On day 5, the stock price is 9. 4 is the closest lower price on day 4. On day 4, the stock price is 4. The only lower price is on day 8. So, the output is [5, 4, 8].

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

Amazon Web Services (AWS) has millions of servers that provide on-demand cloud computing platforms to the customers. In one AWS center, there are nprocesses to be executed and m processors to execute them. The i^th process requires power[i] for execution. A processor can provide power within its range minPower through maxPower[i]. Process i can be executed on processor j if minPower[j] ≤ power[i] ≤ maxPower[j]. Given the power consumption of n processes, the range of processor power in m processors, find: the number of processes which can be executed on the processor the sum of power consumed by the processes that it can serve Function Description Complete the function processExecution in the editor. amazon-process-executionm processExecution has the following parameters:

  • int power[n]: the power consumption of processes
  • int minPower[m]: the minimum bounds of the ranges of processor power
  • int maxPower[m]: the maximum bounds of the ranges of processor power Returns long_int[m][2]: the #th element of this array consists of 2 integers - the number of processes that lie within the range of the #th processor, and the sum of the power consumption of those processes.

Constraints

  • 1 ≤ n ≤ 12 * 10⁵
  • 1 ≤ m ≤ 2 * 10⁵
  • 1 ≤ power[i] ≤ 10⁸
  • 1 ≤ minPower[i] ≤ maxPower[i] ≤ 10⁸

Example 1

Input:

power = [7, 6, 8, 10]
minPower = [6, 3, 4]
maxPower = [10, 7, 9]

Output:

[[4, 31], [2, 13], [3, 21]]

Explanation: The ans for each of the processors are [4, 31], [2, 13], [3, 21], where the first num represents the num of processes, and the second is the sum of power requirements. Return the 2-dimensional array, [[4, 31], [2, 13], [3, 21]]

Example 2

Input:

power = [11, 11, 11]
minPower = [8, 13]
maxPower = [11, 100]

Output:

[[3, 33], [0, 0]]

Explanation: The first processor (minPower[0] = 8, maxPower[0] = 11) can execute all 2 processes, and sum of powers = (11 + 11 + 11) = 33. The second processor (minPower[1] = 13, maxPower[1] = 100) cannot execute any of the processes since none of them lie in its range. Thus, its number of processes = 0 and power consumed = 0.

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

As an aspiring developer at Amazon, you are building a prototype for a cart management service. There is an array of integers, items, that represents the item ids present in the cart initially. Given an array of q integers, query, your service must perform as follows. Each integer is an item id to be added to or removed from the cart. If the query integer is positive, add the integer representing an item id to the back of the cart. If the integer is negative, remove the first occurrence of the integer from the cart. Report an array that represents the final cart after processing all the queries. It is guaranteed that the final cart is non-empty and the integers in the integer Function Description Complete the function processQueriesOnCart in the editor below. processQueriesOnCart has the following parameters:

  • int items[n]: items initially in the cart
  • int query[q]: items to add or remove

Constraints

  • 1 ≤ n, q ≤ 2 * 10⁵
  • 1 ≤ items[i] ≤ 10⁹
  • -10⁹ ≤ query[i] ≤ 10⁹
  • It is guaranteed that query[i] ≠ 0

Example 1

Input:

items = [1, 2, 1, 2, 1]
query = [-1, -1, 3, 4, -3]

Output:

[2, 2, 1, 4]

Explanation: Initially, there are n = 5 items in the cart represented as cart = [1,2,1,2,1] and queries = [-1,-1,3,4,-3] QueryTaskCart -1Delete first 1 from cart[2,1,2,1] -1Delete first 1 from cart[2,2,1] 3Append 3 to cart[2,2,1,3] 4Append 4 to cart[2,2,1,3,4] -3Delete first 3 from cart[2,2,1,4] Report [2,2,1,4] as the final cart.

Example 2

Input:

items = [5, 1, 2, 2, 4, 6]
query = [1, -2, -1, -1]

Output:

[5, 2, 4, 6]

Explanation: items = [5, 1, 2, 2, 4, 6] queries = [1, -2, -1, -1] QueryTaskCart 1Append 1 to cart[5, 1, 2, 2, 4, 6, 1] -2Delete first 2 from cart[5, 1, 2, 4, 6, 1] -1Delete first 1 from cart[5, 2, 4, 6, 1] -1Delete first 1 from cart[5, 2, 4, 6] Report [5, 2, 4, 6] as the final cart.

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

You are given an array wait with elements that represent processes where each element in the array denotes the amount on time that process can wait before needing to be removed. Each second, the next process in the queue is processed and removed from the queue. Additionally, at each second, every process that had a wait time less than or equal to the time passed, needs to be removed. You need to write a function that takes the array wait and returns an array where each element of the array represents the number of processes currently in the queue.

Constraints

N/A

Example 1

Input:

wait = [2,2,3,1]

Output:

[3,1,0]

Explanation: If wait = [2,2,3,1] At time 0: First process is processed and therefore removed, no other processes have a wait time of 0 so nothing else is removed. Now wait = [2,3,1]. Num of processes = 3. answer = [3] At time 1: First process is removed. The process with 1 second wait time is also removed. Now wait = [3]. Num of processes = 1 answer = [3,1] At time 2: First process is removed. No more processes in queue. Now wait = []. Num of processes = 0. answer = [3,1,0] Return [3,1,0]

Example 2

Input:

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

Output:

[4,1,0]

Explanation: n/a for now. If you happen to know about it, pls feel free to lmk!! Manyy thanks in advance!

Example 3

Input:

wait = [3,4,4,4]

Output:

[3,2,1,0]

Explanation: n/a for now. If you happen to know about it, pls feel free to lmk!! Manyy thanks in advance!

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

You are given a list of products and a list of pairs. Each pair means the two products belong to the same category. Category membership is transitive: if product A is in the same category as B, and B is in the same category as C, then A and C are in the same category. Return the size of every final category group, sorted in increasing order. The number of returned sizes is the number of final categories. Function Description Complete the function productCategoryGroupSizes in the editor. productCategoryGroupSizes has the following parameters:

  • String products[]: all product identifiers
  • String pairs[][]: product pairs that belong to the same category Returns int[]: the sorted sizes of the final category groups

Constraints

  • Product identifiers are unique in products.
  • Each pair contains two valid product identifiers.
  • Category membership is transitive.

Example 1

Input:

products = ["A", "B", "C", "D", "E"]
pairs = [["A", "B"], ["B", "C"], ["D", "E"]]

Output:

[2, 3]

Explanation: A, B, and C form one category of size 3. D and E form one category of size 2.

Example 2

Input:

products = ["p1", "p2", "p3", "p4"]
pairs = [["p1", "p2"]]

Output:

[1, 1, 2]

Explanation: Products p3 and p4 are not paired with any other product, so each is its own category.

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

SDE II Another purchaing servers problem for AMZ full-time - Find Max Num Of Servers AWS delivers various computing machines tailored to their customers' deployment and processing requirements. One particular AWS user is looking to acquire some machines for hosting their service. You are provided with details of n machines represented through two lists: power and price. Here, power is a theoretical integer scale indicating the machine’s computing strength, while price specifies the number of AWS credits needed to acquire the machine. For simplicity, each machine has a price value of either 1 or 2. Your task is to determine the least possible overall price to obtain a collection of machines such that the cumulative power is at least a given threshold target. If no selection of machines can achieve a total power that meets or surpasses target, return -1. Note: A machine can only be chosen once. Function Description Complete the function minCostToPurchaseServers in the editor. minCostToPurchaseServers has the following parameters:

    1. int[] power: a list of integers denoting the computational strength of the machines
    1. int[] price: a list of integers indicating the cost of the machines
    1. int target: the minimum required total computational strength Returns int: the least total cost to obtain machines, or -1 if it’s unachievable

Example 1

Input:

power = [4, 4, 6, 7]
cost = [1, 1, 2, 2]
target = 7

Output:

2

Explanation: If we go with machines at positions [0, 1], the total price is 1 + 1 = 2, which is the lowest, and the combined power is 4 + 4 = 8, which meets the requirement of being at least target. Selecting machines [0, 2] results in a total price of 1 + 2 = 3 and total power of 4 + 6 = 10 Choosing [1, 2] gives the same outcome: price = 3, power = 10. Other combinations can be considered similarly. Among all valid choices, the selection [0, 1] yields the smallest total price (which is 2) while ensuring the accumulated power surpasses the given threshold target = 7.

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

You are given a binary string, binary, consisting only of characters '0' and '1'. You are allowed to perform the following operation zero or more times: Choose any subsequence of binary. Sort this subsequence. Replace the chosen subsequence in binary with its sorted version. Additionally, you are given an array arr of length n, where each element of arr is a string of the same length as binary. Each string in arr consists of characters '0', '1', and the wildcard character '?'. The '?' character can be replaced with either '0' or '1' arbitrarily. For each string in arr, after replacing every '?' character with either '0' or '1', you need to determine whether it is possible to rearrange the binary string into the modified string using the sorting operation described above. If it is possible, store "YES" as the corresponding answer; otherwise, store "NO". Notes:

  • A subsequence of a string is obtained by deleting some (possibly zero) characters from the string without changing the order of the remaining characters.
  • Each computation for the elements of arr is independent of the others. The binary string is reset to its original state before checking each string in arr.

Example 1

Input:

binary = "101100"
arr = ["?110?1", "111???"]

Output:

["YES", "NO"]

Explanation: Consider the binary string binary = "101100" and the array arr = ["?110?1", "111???"].

  • For arr[0] = "?110?1", you can replace the '?' characters to form the string "011001". It is possible to rearrange the binary string into "011001" using the sorting operations:
  • Choose the subsequence {0, 2}, and sorting it transforms binary to "011100".
  • Choose the subsequence {3, 4, 5}, and sorting it transforms binary to "011001". The answer for this element is "YES".
  • For arr[1] = "111???", no valid replacement of '?' characters allows the binary string to be rearranged to match the resulting string. Therefore, the answer is "NO". Thus, the output for this case would be ["YES", "NO"].
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are working on an Amazon Data Center where you are required to reduce the amount of main memory consumption by the processes. Given list of processes where each value representing memory consumption by the processes and given one variable m representing number of processes to be removed. We need to delete m number of processes from the list in contiguous manner and return minimum amount of main memory used by all the processes running after deleting contiguous segment of processes. Function Description Complete the function reduceMemoryUsage in the editor. reduceMemoryUsage has the following parameters:

  • int[] processes: an array of integers representing memory consumption by the processes
  • int m: the number of processes to be removed Returns int: the minimum amount of main memory used after deleting a contiguous segment of processes

Constraints

  • 1 < N < 1000000000 //size of the array
  • 1 < m < 100000 //contiguous segment of the array.
  • 1 < process[i] < 1000000000

Example 1

Input:

processes = [10, 4, 8, 13, 20]
m = 2

Output:

22

Explanation: Removing 13 and 20 as they are consuming large memory. The remaining processes consume 10 + 4 + 8 = 22 units of memory, which is the minimum possible.

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

As an intern at Amazon, you have been assigned a task to implement the three sign in pages, each with its own API: Register, Login, Logout. Notes:

  • Initially, there are no users registered.
  • If a user is already logged in and makes a login request, the new request is unsuccessful. The original login remains active.
  • Each log is an API request and is in one of the three allowed formats.
  • The order of execution of each requests is the same as order of the input.
  • The username and passwords are case-sensitive. Given a log of API reqeuests, return the list of returns from the mock website. Function Description Complete the function signInPages in the editor. signInPages has the following parameter:
  • String[] requests: an array of API requests Returns String[]: an array of responses for each API request
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

There's a computer system owned by an Amazon user. This system is equipped with n CPU cores, each with a specific temperature denoted by temperature[]. The user, let's call them the Optimizer, is keen on enhancing the performance of their machine by regulating the core temperatures. In a single operation, the Optimizer can choose one of the following techniques: Select a position i (0 ≤ i Select a position i (0 ≤ i Increase the temperature of all cores by 1. Formally, given an array temperature of size n, the initial temperature of each core, find the minimum number of actions required for the Optimizer, to make the temperature of each core equal to 0. Function Description Complete the function regulateTemperatures in the editor below. regulateTemperatures has the following parameter:

  • int temperature[n]: initial temperature of each core Returns long: the minimum number of actions required to make the temperature of each core equal to 0.

Example 1

Input:

temperature = [2, 4, 4]

Output:

4

Explanation: One of the optimal ways to make the temperature of all cores 0 is as follows:

  • Select index 1 and use the ability of type 2. The new temperatures will be [2, 3, 3].
  • Select index 2 and use the ability of type 1. The new temperatures will be [1, 2, 2].
  • Select index 1 and use the ability of type 2. The new temperatures will be [1, 1, 1].
  • Select index 2 and use the ability of type 1. The new temperatures will be [0, 0, 0]. It can be shown that it is not possible to make the temperature of each core equal to 0 in less than 4 actions, hence, the answer is 4.

Example 2

Input:

temperature = [2, -2, -3, 1]

Output:

10

Explanation: One of the optimal ways to make the temperature of all cores 0 is as follows: Select index 3 and use the ability of type 2. The new temperatures will be [2, -2, -3, -2]. Select index 1 and use the ability of type 1. The new temperatures will be [1, -3, -3, -21. Use the ability of type 3. The new temperatures will be [2, -2, -2, -1]: Select index 3 and use the ability of type 2. The new temperatures will be [2, -2, -2, -2]. Select index 0 and use the ability of type 1. The new temperatures will be [1, -2, -2, -2]. Select index 0 and use the ability of type 1. The new temperatures will be [O, -2, -2, -2]. Use the ability of typé 3. The new temperatures will be [1, -1, -1, -1]. Use the ability of type 3. The new temperatures will be [2, 0, 0, 0]. Select index 0 and use the ability of type 1. The new temperatures will be [1, 0, 0, 0]. It can be shown that it is not possible to make the temperature of each core equal to 0 in less than 10 actions, hence, the answer is 10.

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

(Look into LC 664. Strange Printer may help :) Given a string, determine the minimum number of operations (deletions) required to make the string empty. You can perform the deletion operation as many times as you prefer:: Pick any group of consecutive chars in the string, with a group size s ranging from 1 up to the curr len of the string. Delete them only when all the chars in this group are the same. Function Description Complete the function minimumOperationsToRemove in the editor. minimumOperationsToRemove has the following parameter:

  • String s: the string to be processed Returns int: the minimum number of operations required

Example 1

Input:

s = "abaca"

Output:

3

Explanation: Pick s = 1: remove "b" -> "aaca" Pick s = 1: remove "c" -> "aaa" Pick s = 3: since all the a's are together remove all a's at once. Now it is empty. We can make the input string empty in just 3 operations. So, we return 3 as the answer.

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

As an intern at Amazon, you have been assigned a task to implement the sign-in pages in the Amazon Dummy Website. There are three sign-in pages, each with its own API: Given a log of API requests, return the list of returns from the mock website. Notes: Initially, there are no users registered. If a user is already logged in and makes a login request, the new request is unsuccessful. The original login remains active. Each log is an API request and is in one of the three allowed formats. The order of execution of each request is the same as the order of input. The usernames and passwords are case-sensitive. Function Description Complete the function returnRecords in the editor below. returnRecords has the following parameter: string attempts[n]: each of the API requests Returns

  • string[n]: an array of strings where #th string is the return value of the #th API request

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ |username|, |password| ≤ 10 (where |s| is the length of string s)
  • username and password are alphanumeric strings, ranges [0-9, a-z, A-Z]

Example 1

Input:

attempts = ["register user05 qwerty", "login user05 qwerty", "logout user05"]

Output:

["Registered Successfully", "Logged In Successfully", "Logged Out Successfully"]

Explanation: Check out the example image above

Example 2

Input:

attempts = ["register david david123", "register adam 1Adam1", "login david david123", "login adam 1adam1", "logout david"]

Output:

["Registered Successfully", "Registered Successfully", "Logged In Successfully", "Login Unsuccessfully", "Logged Out Successfully"]

Explanation:

  • register david david123: There is not user with the username "david" registered, so the registration is successful
  • register adam 1Adam1: There is not user with the username "adam" registered, so the registration is successful
  • login david david123: The username and the password for the user match with that in the database, so the login is successful
  • login adam 1adam1: The password("1adam1") does not match the actual password ("1Adam1"), so the login is unsuccessful
  • logout david: The user "David" is logged in currently, so the logout is successful
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given a binary string. Find the minimum number of operations required to reverse it. An operation is defined as: Remove a character from any index and append it to the end of the string. Function Description Complete the function reverseBinaryString in the editor. reverseBinaryString has the following parameter:

  • String s: a binary string Returns int: the minimum number of operations required to reverse the binary string

Constraints

1 ≤ S.length ≤ 1e5

Example 1

Input:

s = "00110101"

Output:

3

Explanation: Here is one way to reverse the string in 3 operations:

  • 00110101 - 00101011 (index 3 was appended at the end)
  • 00101011 - 01010110 (index 0 was appended at the end)
  • 01010110 - 10101100 (index 0 was appended at the end) So the answer here is 3 operations.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Amazon allows customers to add reviews for the products they bought from their store. The review must follow Amazon's community guidelines in order to be published. Suppose that Amazon has marked n strings that are prohibited in reviews. They assign a score to each review that denotes how well it follows the guidelines. The score of a review is defined as the longest contiguous substring of the review which does not contain any string among the list of words from the prohibited list, ignoring the case. Given a review and a list of prohibited string, calculate the review score. Function Description Complete the function findReviewScore in the editor. findReviewScore has the following parameters: review: a string string prohibitedWords[n]: the prohibited words Returns int: the score of the review

Constraints

  • 1 ≤ |review| ≤ 10⁵
  • 1 ≤ n ≤ 10
  • 1 ≤ prohibitedWords[i] ≤ 10
  • review consists of English letters, both lowercase and uppercase
  • prohibitedWords[i] consists of lowercase English letters

Example 1

Input:

review = "GoodProductButScrapAfterWash"
prohibitedWords = ["crap", "odpro"]

Output:

15

Explanation: Some of the substrings that do not contain a prohibited word are:

  • ProductBut
  • rapAfterWash
  • dProductButScu
  • Wash The longest substring is "dProductButScra", return its length, 15.

Example 2

Input:

review = "FastDeliveryOkayProduct"
prohibitedWords = ["eryoka", "yo", "eli"]

Output:

11

Explanation: The substring "OkayProduct" is the longest substring which does not contain a prohibited word. Its length is 11.

Example 3

Input:

review = "ExtremeValueForMoney"
prohibitedWords = ["tuper", "douche"]

Output:

20

Explanation: The review does not contain any prohibited word, so the longest substring is "ExtremeValueForMoney", length 20.

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

You are given a 2D grid board that represents a chessboard. The board contains multiple cells, where: 0 indicates an empty cell. 1 indicates a cell containing a rook. A rook can only move vertically or horizontally if there is another rook in its row or column to capture. It cannot move if there are no other rooks in its row or column. Your task is to determine the minimum number of rooks that can be left on the board in a peaceful state after capturing as many rooks as possible. A peaceful state is defined as a state where no two rooks can capture each other (i.e., no two rooks share the same row or column). Note: Rook Movement: A rook can only move if there is another rook in the same row or column to capture. If a rook is alone in its row or column, it cannot move. The goal is to minimize the number of rooks left by capturing as many rooks as possible, while ensuring that the remaining rooks are in a peaceful state. A peaceful state is achieved when no two rooks can capture each other (i.e., no two rooks share the same row or column).

Constraints

  • The dimensions of the board are `1

Example 1

Input:

board = [[1, 0, 1, 0, 0], [1, 0, 1, 0, 0], [1, 0, 1, 1, 0]]

Output:

1

Explanation: All the rooks are connected either directly or indirectly in the same row or column, forming one single connected group.

Example 2

Input:

board = [[0, 0, 1, 0, 0], [1, 0, 1, 0, 0], [1, 0, 0, 0, 1], [0, 0, 1, 1, 0]]

Output:

1

Explanation: All the rooks can reach each other, either directly or through a sequence of moves along rows or columns, resulting in one connected component.

Example 3

Input:

board = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]

Output:

3

Explanation: There are 3 rooks, and none of them share the same row or column. Thus, each rook is isolated, resulting in 3 connected components.

Example 4

Input:

board = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]

Output:

1

Explanation: All rooks are connected in both rows and columns, forming one single connected component.

Example 5

Input:

board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Output:

0

Explanation: There are no rooks on the board.

Example 6

Input:

board = [[1]]

Output:

1

Explanation: There is single rook, resulting in one connected component.

Example 7

Input:

board = [[1, 0], [1, 0]]

Output:

1

Explanation: The two rooks are in the same row, forming one connected group.

Example 8

Input:

board = [[1, 0, 0], [1, 0, 0], [0, 0, 1]]

Output:

2

Explanation: The two rooks in the first two rows share the sam column, forming one connected component.The rook in the third row is isolated, resulting in a total of two connected components.

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

You have an integer servers, wh

Constraints

N/A

Example 1

Input:

servers = 5
requests = [3, 1, 0, 2, 1]

Output:

[0, 1, 0, 2, 1]

Explanation: An unknown myth for now If you know about it, I’d be delighted to hear from you! You da best!

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

In managing tasks at analytics platform, the goal is to efficiently schedule both primary and secondary tasks within specified time constraints. There are n primary tasks and n secondary tasks. Two arrays, primary and secondary, provide information on task hours, where primary[i] represents the duration in hours of the ith primary task, and secondary[i] represents the duration in hours of the ith secondary task. Each day on the platform has a time limit denoted as limit hours. One primary task must be scheduled each day. If time remains after the primary task, you can choose to schedule at most one secondary task on that day. It's essential to ensure that the total hours does not exceed the specified limit hours. Determine the maximum number of secondary tasks that can be scheduled during these n days while adhering to the given constraints.

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

Amazon Web Services (AWS) provides highly scalable solutions for applications hosted on their servers. A company using AWS is planning to scale up horizontally and wants to buy servers from a list of available options. Find the maximum number of servers (as a subsequence from the list) that can be rearranged so that the absolute difference between adjacent servers (including circular adjacency) is ≤ 1. Conditions:

  • A circular sequence is formed → So first and last servers are also considered adjacent.
  • A subsequence means elements can be removed but the order is preserved. Formal: Given an array powers[] of n integers: Find the maximum subsequence length such that it can be rearranged into a circular array where abs(a[i] - a[i+1]) ≤ 1 for all i, and abs(a[m-1] - a[0]) ≤ 1 where m is the length of the subsequence.

Example 1

Input:

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

Output:

4

Explanation: Valid Candidates:

  • [1, 2, 2, 1] → valid circular arrangement
  • [3, 1, 2, 2] → can be rearranged to [1, 2, 3, 2] which is valid Invalid:
  • [3, 1, 2] → no rearrangement makes circular adjacent difference ≤ 1 ans should be 4..
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

People browsing Amazon frequently rely on product feedback to make buying decisions. They may narrow down their search using specific phrases, but spelling errors often appear in reviews. To handle this issue, Amazon's system also considers review sections that contain words nearly matching the search phrase. A text fragment phrase is nearly identical to another string target if you can swap two neighboring characters in phrase at most once to make it identical to target. Your task is to determine the number of continuous sections within content that are nearly identical to target. Note: A continuous section means consecutive characters inside a string. Two sections are distinct if they start from different indices.

Constraints

  • target and content will consist solely of lowercase English letters.
  • 1 ≤ |target| ≤ |content| ≤ 50, where |s| denotes the length of a string s.

Example 1

Input:

target = "moon"
content = "monomon"

Output:

2

Explanation: Take the first four letters from content, which is "mono". By swapping the last two letters, it becomes identical to the target "moon". Next, observe the final four letters in content, which is "onom". Swapping the first two characters transforms it into the target. Therefore, there are 2 continuous sections in "monom" that are nearly identical to "moon". Note that no other segment within the content qualifies as similar to the given target.

Example 2

Input:

target = "aaa"
content = "aaaa"

Output:

2

Explanation: There are 2 substrings of "aaaa" that are similar to "aaa" are: aaaa aaaa

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

You are given an integer array codes representing error codes. Sort the entire array using these priority rules:

  • Error codes with lower frequency come first.
  • If two error codes have the same frequency, the smaller numeric value comes first. Return the sorted array, keeping duplicate values in the result. Function Description Complete the function sortErrorCodesByFrequency in the editor below. sortErrorCodesByFrequency has the following parameter:
  • int[] codes: the input error codes Returns int[]: the reordered array.

Constraints

  • The output must contain the same multiset of values as the input.
  • Order by increasing frequency, then by increasing numeric value.

Example 1

Input:

codes = [4, 5, 6, 5, 4, 3]

Output:

[3, 6, 4, 4, 5, 5]

Explanation: 3 and 6 appear once, so they come first in numeric order. Then 4 and 5 each appear twice, so 4 comes before 5.

Example 2

Input:

codes = [2, 2, 1, 1, 1, 3]

Output:

[3, 2, 2, 1, 1, 1]

Explanation: 3 has frequency 1, 2 has frequency 2, and 1 has frequency 3.

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

Amazon has millions of products sold on its e-commerce website, and each product is identified by its product code. Given an array of n productCodes and order, a string that represents the precedence of characters, sort the productCodes in lexicographically increasing order per the precedence. Note: Lexicographical order is defined in the following way. When we compare strings s and t, first we find the leftmost position with differing characters: s_l and t_l. If there is no such position (i.e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters s_l and t[i] according to their order in the given precedence order. Function Description Complete the function sortProductCodes in the editor below. sortProductCodes has the following parameter(s):

  • string order: the new precedence order string
  • productCodes[n]: the array to sort Returns string[n]: the productCodes array in sorted order

Constraints

  • 1 ≤ n &l

Example 1

Input:

order = "abcdefghijklmnopqrstuvwxyz"
productCodes = ["adc", "abc"]

Output:

["abc", "adc"]

Explanation: Consider the strings "adc" and "abc", the first point of difference is at position 1 (assuming start index is 0), and 'd'>'b' according to the given precedence order.

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

Amazon Prime Day is a day where many items are put on sale for Amazon Prime members. A list of sale items is assembled where each item is assigned a category denoted by a lowercase English letter. Since the sale is to be held on two different days, the company has decided to split the list of items into two contiguous non-empty sub-lists - a prefix and a suffix. To ensure that both days share a sufficient number of similar items, they also need to split it in a way such that the number of distinct categories shared by both sub-lists is greater than k. Formally, given a string, categories, find the number of ways to split the string into exactly two contiguous non-empty substrings such that the number of distinct characters occurring in both the substrings is greater than a given integer k. Function Description Complete the function splitPrefixSuffix in the editor. splitPrefixSuffix has the following parameters:

  • string categories: the categories
  • int k: shared distinct categories must be greater than this value Returns int: the number of ways to split the given string

Constraints

  • 1 ≤ length(categories) ≤ 10⁵
  • 0 ≤ k ≤ 26
  • The string c

Example 1

Input:

categories = "abbcac"
k = 1

Output:

2

Explanation:

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

Hello! I feel like it's a duplicate of another existing problem..but I couldnt find it. If you happen to know the duplicate, please let me know. Manyyyy thanks in advance. You are the best! There are data points as integer array and array of queries. Where each query is: q[i][0] = old value, q[i][1] = new value. After processing i-th query you need to update all data points having value 'old value' to 'new value' and calculate total sum of all data points. Return array of sums after each query executed. Watch out for special cases like duplicates and zero updates (same value or value doesn't exist in the current array). Function Description Complete the function getSumAfterQueries in the editor. getSumAfterQueries has the following parameters:

    1. int[] data: an array of integers representing the data points
    1. int[][] queries: an array of queries where queries[i][0] is the old value and queries[i][1] is the new value Returns int[]: an array of integers representing the sum of data points after each query
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given an integer array arr and an integer requests. Repeat the following operation exactly requests times:

  • Find the current maximum value and the current minimum value in arr.
  • Add their sum to the answer.
  • Choose one occurrence of the maximum value and decrease it by 1. Return the final accumulated answer. Function Description Complete the function sumMaxPlusMinAfterOperations in the editor below. sumMaxPlusMinAfterOperations has the following parameters:
  • int[] arr: the initial values
  • int requests: the number of operations Returns long: the accumulated sum.

Constraints

  • requests ≥ 0
  • Each operation decreases one occurrence of the current maximum value by exactly 1.
  • Use a wide enough integer type for the accumulated total.

Example 1

Input:

arr = [1, 2]
requests = 2

Output:

5

Explanation: First add 1 + 2 = 3 and decrement the 2 to 1. Then add 1 + 1 = 2. The total is 5.

Example 2

Input:

arr = [3, 3, 3]
requests = 1

Output:

6

Explanation: The current maximum and minimum are both 3, so the answer increases by 6.

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

Data analysts at Amazon are analyzing time series data. It was concluded that the data of the nth item was dependent on the data of the some xth day if there is a positive integer k such that the floor (n/k) = x where floor(z) represents the largest integer less than or equal to z. Given n, find the sum of all the days numbers on which the data of the xth (0 ≤ x ≤ n) will be dependent. Function Description Complete the function sumOfAllDaysNumbers in the editor. sumOfAllDaysNumbers has the following parameter:

  • int n: the nth item Returns int: the sum of all the days numbers on which the data of the xth will be dependent 𓂃 ོ𓂃 A Supa Huge THANK YOU to Lie 𓂃𓆟𓂃 𓈒𓏸

Example 1

Input:

n = 5

Output:

8

Explanation: For n = 5, the days on which the data of the xth will be dependent are calculated as follows: x k floor(n/k) 0 6 0 1 5 1 2 2 2 3 does not exist - 4 does not exist - 5 1 5 The sum of all days numbers is 0 + 1 + 2 + 5 = 8.

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

Find the sum of the maximum of all subarrays multiplied by their length in O(n). For example, given an array arr = [4,2,1,2], the output should be 59. Function Description Complete the function sumOfMaxOfSubarrays in the editor. sumOfMaxOfSubarrays has the following parameter:

  • int[] arr: an array of integers Returns long integer: the sum of the maximum of all subarrays multiplied by their length

Example 1

Input:

arr = [4, 2, 1, 2]

Output:

59

Explanation: Here's how the sum is calculated: [4] 1 4 1 * 4 = 4 [4, 2] 2 4 2 * 4 = 8 [4, 2, 1] 3 4 3 * 4 = 12 [4, 2, 1, 2] 4 4 4 * 4 = 16 [2] 1 2 1 * 2 = 2 [2, 1] 2 2 2 * 2 = 4 [2, 1, 2] 3 2 3 * 2 = 6 [1] 1 1 1 * 1 = 1 [1, 2] 2 2 2 * 2 = 4 [2] 1 2 1 * 2 = 2 Sum == 59

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

AMZ Interval Collection (A group of problems focused on operations involving intervals :) -

  1. Task Scheduler (Full-Time)
  2. Merge Intervals (Intern, NG)
  3. Find Overlapping Times (Intern)
  4. Get Maximum Sum Find Overlapping Times (Full-Time)
  5. Optimal Interval Difference Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. You are given an array of CPU tasks, each labeled with a letter from A to Z, and a number n. Each CPU interval can be idle or allow the completion of one task. Tasks can be completed in any order, but there's a constraint: there has to be a gap of at least n intervals between two tasks with the same label. Return the minimum number of CPU intervals required to complete all tasks. Function Description Complete the function leastInterval in the editor. leastInterval has the following parameters:
    1. char[] tasks: an array of uppercase English letters representing tasks
    1. int n: the cooling interval Returns int: the minimum number of intervals to complete all tasks

Constraints

  • 1 ≤ tasks.length ≤ 10⁴
  • tasks[i] is an uppercase English letter.
  • 0 ≤ n ≤ 100

Example 1

Input:

tasks = ["A","A","A","B","B","B"]
n = 2

Output:

8

Explanation: A possible sequence is: A -> B -> idle -> A -> B -> idle -> A -> B. After completing task A, you must wait two intervals before doing A again. The same applies to task B. In the 3rd interval, neither A nor B can be done, so you idle. By the 4th interval, you can do A again as 2 intervals have passed.

Example 2

Input:

tasks = ["A","C","A","B","D","B"]
n = 1

Output:

6

Explanation: A possible sequence is: A -> B -> C -> D -> A -> B. With a cooling interval of 1, you can repeat a task after just one other task.

Example 3

Input:

tasks = ["A","A","A","B","B","B"]
n = 3

Output:

10

Explanation: A possible sequence is: A -> B -> idle -> idle -> A -> B -> idle -> idle -> A -> B. There are only two types of tasks, A and B, which need to be separated by 3 intervals. This leads to idling twice between repetitions of these tasks.

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

In the Amazon Trade Optimization System, a financial strategist named Joe the trader is assigned the task of maximizing revenue while following the execution rules for trade operations. The trading system includes 26 distinct operation types, labeled from 'A' to 'Z'. The strategist is provided with n operations to perform, where the i-th operation is denoted by the string element task[i], and the related revenue is specified by the array reward[i]. According to the trade rules, no more than k identical operations can be executed consecutively. For instance, if k = 2 and the operation sequence is "bccc", this is invalid because 'c' is repeated three times in succession. On the other hand, if the sequence is "bcbcc", the trade is considered valid. To maintain a valid sequence, the trader might need to skip certain operations. Determine the maximum possible revenue the trader can earn by omitting specific operations while keeping the sequence valid.

Constraints

:O

Example 1

Input:

tasks = "BAAAB"
rewards = [1, 4, 2, 10, 3]
k = 2

Output:

18

Explanation: The best strategy is to skip the task at index 2 (tasks[2] = 'A'). The sequence then becomes "BAAB", leading to a total gain of 1 + 4 + 10 + 3 = 18.

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

You are given an undirected tree with nodes numbered from 0 to n - 1, rooted at node 0. For two queried nodes, classify their relationship. Return "siblings" if the two nodes have the same parent. Return "cousins" if they are at the same depth but have different parents. Otherwise, return "others".

Constraints

The input graph is a valid tree rooted at node 0. Both queried nodes are valid node ids.

Example 1

Input:

n = 7
edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]
nodeA = 3
nodeB = 4

Output:

"siblings"

Explanation: Nodes 3 and 4 share parent 1.

Example 2

Input:

n = 7
edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]
nodeA = 3
nodeB = 5

Output:

"cousins"

Explanation: Nodes 3 and 5 are both depth 2, but their parents are different.

Example 3

Input:

n = 7
edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]
nodeA = 1
nodeB = 6

Output:

"others"

Explanation: The two nodes are at different depths.

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

Complete the function below. The function receives the full standard input as a single string and returns the exact standard output lines. Given an integer array and a target value, return all unique pairs whose sum equals the target. Each pair must be sorted in ascending order, and duplicate pairs must appear only once. Output the pairs in lexicographic order as a,b. If there are no valid pairs, output None. Function Description Complete solveUniquePairsWithTargetSum. It has one parameter, String input. The first line contains n target; the second line contains n integers. Return one output line per unique pair.

Constraints

Pairs are value pairs, not index pairs; duplicates in the input should not create duplicate output lines.

Example 1

Input:

input = "8 5\n1 4 2 3 3 2 0 5"

Output:

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

Explanation: The pair 2,3 is output once even though both values appear multiple times.

Example 2

Input:

input = "4 10\n1 2 3 4"

Output:

["None"]

Explanation: No pair sums to 10.

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

Amazon operates a system of n warehouses, each represented by warehouse[i], where warehouse[i] indicates the maximum number of items that particular warehouse can hold. Additionally, there are q shipments to process, represented by a 2D array catalog[i][2]. Each shipment has specific requirements: catalog[i][0] denotes the minimum capacity that the selected warehouse must have to accommodate the shipment. catalog[i][1] denotes the minimum combined capacity required from the other warehouses to fulfill backup storage needs. Amazon can increase the capacity of any warehouse by spending 1 token per unit of capacity. The task is to determine the optimal strategy for allocating capacity for each shipment such that the fewest number of tokens are expended. This strategy must ensure that the selected warehouse meets the required capacity for the shipment and that the combined capacity of the other warehouses is sufficient for backup storage. Note The tokens are spent independently for each shipment If warehouse i is selected to accommodate the shipment and if there are some left over capacity (i.e., warehouse[i] - catalog[i][0] > 0) then it cannot be used for backup storage. Function Description Complete the function useMinimumTokens in the editor. useMinimumTokens has the following parameters:

  • int warehouse[n]: an array listing the initial maximum capacity of each warehouse.
  • long catalog[q][2]: A 2D array describing the shipments. Returns long[q]: An array representing the minimum number of tokens needed to serve each shipment while ensuring sufficient backup storage.

Constraints

  • 2 ≤ n ≤ 10⁵
  • 1 ≤ warehouse[i] ≤ 10⁹
  • 1 ≤ q ≤ 10⁵
  • 1 ≤ catalog[i][0] ≤ 10⁹
  • 1 ≤ catalog[i][1] ≤ 10¹⁵

Example 1

Input:

warehouse = [2, 4, 1, 3]
catalog = [[5, 7]]

Output:

[TO-DO]

Explanation: If the first warehouse is expanded for the shipment, 3 tokens are needed for the first warehouse to accommodate the shipment, and no tokens are needed for the rest of the warehouses to maintain backup storage. Hence, the total tokens needed = 3 + 0 = 3. If the second warehouse is expanded for the shipment, 1 token is needed for the second warehouse to accommodate the shipment, and 1 token is needed for the rest of the warehouses to maintain backup storage. Hence, the total tokens needed = 1 + 1 = 2. If the third warehouse is expanded for the shipment, 4 tokens are needed for the third warehouse to accommodate the shipment, and no tokens are needed for the rest of the warehouses to maintain backup storage. Hence, the total tokens needed = 4 + 0 = 4. If the fourth warehouse is expanded for the shipment, 2 tokens are needed for the fourth warehouse to accommodate the shipment, and no tokens are needed for the rest of the warehouses to maintain backup storage. Hence, the total tokens needed = 2 + 0 = 2.

Example 2

Input:

warehouse = [5, 1, 1, 4]
catalog = [[5, 7], [4, 10], [7, 9]]

Output:

[1, 3, 5]

Explanation: For the first shipment, the optimal selection is warehouse number four. You’ll need to spend one token to extend the capacity of the fourth warehouse to accommodate the shipment and no tokens on the other warehouses. The total tokens spent equal one for capacity augmentation + zero for backup storage = 1. For the second shipment, the optimal selection is either the second or third warehouse. You’ll spend three tokens to extend the capacity of the selected warehouse and no tokens on the remaining warehouses. Hence, the total tokens spent equal three for augmentation + zero for backup storage = 3. This explanation is incomplete. Will enhance it later.

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

There are multiple VM types, each with an initial stock count. A sequence of custo

Constraints

  • Stocks are non-negative integers.
  • The number of requests may be as large as the total available stock.

Example 1

Input:

vmStock = [1, 2, 4]
customerRequests = 4

Output:

15

Explanation: The rental costs are 5, 4, 3, and 3, for a total revenue of 15.

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

You are given an integer array arr of size n, where arr[i] represents the threshold of the i-th robot. Each robot can be assigned one of two states: Running or Waiting. A configuration is valid if all robots satisfy the following conditions: If a robot is Running, then the total number of running robots must be ≥ arr[i]. If a robot is Waiting, then the total number of waiting robots must be < arr[i]. Each robot must be assigned exactly one state. A configuration is valid only if no robot violates its condition. Return the total number of valid configurations.

Constraints

1 ≤ n ≤ 10⁵ 1 ≤ arr[i] ≤ n

Example 1

Input:

arr = [1,2]

Output:

2

Explanation: n=2. Config 1: robot-0 Running, robot-1 Waiting. Running count=1 ≥ arr[0]=1 . Waiting count=1 = arr[0]=1 , 2 ≥ arr[1]=2 . No waiting robots to check. Valid. Config "both Waiting": waiting count=2, robot-0 needs 2 = arr[1]=2? 1 ≥ 2 . Invalid. Total = 2.

Example 2

Input:

arr = [2,2]

Output:

1

Explanation: n=2. Both Running: running count=2 ≥ arr[0]=2 , 2 ≥ arr[1]=2 . Valid. All other configs fail: running count 0 or 1 cannot satisfy arr[i]=2 for a Running robot, and waiting count 1 or 2 cannot satisfy < arr[i]=2 for a Waiting robot (1 < 2 but a single Running robot fails its own condition). Total = 1.

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

You are given an initial parentheses sequence represented by the string s, along with a Parentheses Perfection Kit containing different types of parentheses in the form of the string kitParentheses and their respective efficiency ratings in the efficiencyRatings array (both of size m). The EfficiencyScore of the original string s is initially 0. You can use any number of unused parentheses from the kit to create the final sequence, as long as the final sequence remains balanced. The task is to determine the maximum possible EfficiencyScore that can be achieved for the resulting balanced sequence. Note: It is guaranteed that the sequence can be made balanced by adding zero or more parentheses from the kit.

Constraints

  • 1 ≤ |s| < 2 * 10⁵
  • 0 ≤ m < 2 * 10⁵
  • -10⁹ ≤ efficiencyRatings[i] ≤ 10⁹
  • Both strings s and kitParentheses consist of opening and closing parentheses only

Example 1

Input:

s = ")(("
kitParentheses = ")(()))"
m = 6
efficiencyRatings = [3, 4, 2, -4, -1, -3]

Output:

TO-DO

Explanation: TO-DO: Add explanation for the example here.

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

Amazon would like to enforce a password policy that when a user changes their password, the new password cannot be similar to the current one. To determine whether two passwords are similar, they take the new password, choose a set of indices and change the characters at these indices to the next cyclic character exactly once. Character 'a' is changed to "b", 'b' to 'c' and so on, and 'z' changes to 'a'. The password is said to be similar if after applying the operation, the old password is a subsequence of the new password. The developers come up with a set of n password change requests, where newPasswords denotes the array of new passwords and oldPasswords denotes the array of old passwords. For each pair newPasswords[i] and oldPassword[i], return "YES" if the passwords are similar, that is newPasswords[i] becomes a subsequence of oldPasswords[i] after performing the operations, and "NO" otherwise. Note A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. Function Description Complete the function checkSimilarPasswords in the editor. checkSimilarPasswords has the following parameters: string newPasswords[n]: newPasswords[i] represents the new password of the ith pair string oldPasswords[n]: newPasswords[i] represents the old password of the ith pair Returns string[n]: the ith string represents the answer to the ith pair of passwords.

Constraints

  • 1 ≤ n ≤ 10
  • Sum of lengths of all passwords in array newPassword and array oldPasswords does not exceed (2 * 10⁵)
  • |oldPasswords[i] ≤ |newPasswords[i]| for all i

Example 1

Input:

newPasswords = ["baacbab", "accdb", "baacba"]
oldPasswords = ["abdbc", "ach", "abb"]

Output:

["YES", "NO", "YES"]

Explanation: Consider the first pair: newPasswords[0] = "baacbab" and oldPasswords = "abdbc". Change "ac" to "bd" at the 3rd and 4th positions, and "b" to "c" at the last position. The answer for this pair is YES. The newPasswords[1] = "accdb" and oldPasswords = "ach". It is not possible to change the character of the new password to "h" which occurs in the old password, so there is no subsequence that matches. The answer for this pair is NO. newPasswords[2] = "baacba" and oldPasswords = "abb". The answer for this pair is YES. Eventually, we return ["YES", "NO", "YES"].

Example 2

Input:

newPasswords = ["aaccbbee", "aab"]
oldPasswords = ["bdbf", "aee"]

Output:

["YES", "NO"]

Explanation: For i = 0; newPasswords[0] = "aaccbbee", oldPasswords[0] = "bdbf" For i = 1, newPassword[1] = "aab", oldPasswords[1] = "aee". It is impossible to get string oldPasswords[1] as the subsequence of newPasswords[1] by performing the operation. Eventually, we return ["YES", "NO"].

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

Amazon is hosting a team hackathon.

    1. Each team will have exactly teamSize developers.
    1. A developer's skill level is denoted by skill[i].
    1. The difference between the maximum and minimum skill levels within a team cannot exceed a threshold, maxDiff. Determine the maximum number of teams that can be formed from the contestants. Complete the function countMaxNumTeams which has the following parameters
  • int skill[n]: the developers' skill levels
  • int teamSize: the number of developers to make up a team
  • int maxDiff: the threshold value. int: the maximum number of teams that can be formed at one time

Constraints

1 ≤ teamSize ≤ n ≤ 10⁵ 1 ≤ maxDiff ≤ 10⁹ 1 ≤ skill[i] ≤ 10⁹ Only one valid answer exists.

Example 1

Input:

skill = [3, 4, 3, 1, 6, 5]
teamSize = 3
maxDiff = 2

Output:

2

Explanation: At most, 2 teams can be formed: [3, 3, 1] and [4, 6, 5].The difference between the maximum and minimum skill levels is 2 in each case, which does not exceed the threshold value of 2

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

A team of analysts at Amazon needs to analyze the stock prices of Amazon over a period of several months. A group of consecutively chosen months is said to be maximum profitable if the price in its first or last month is the maximum for the group. More formally, a group of consecutive months [l, r] (1 ≤ l ≤ r ≤ n) is said to be maximum profitable if either: stockPrice[l] = max(stockPrice[l], stockPrice[l + 1], ..., stockPrice[r])

  • or, stockPrice[r] = max(stockPrice[l], stockPrice[l + 1], ..., stockPrice[r]) Given prices over n consecutive months, find the number of maximum profitable groups which can be formed. Note that the months chosen must be consecutive, i.e., you must choose a subarray of the given array. Function Description Complete the function countMaximumProfitableGroups function in the editor below. countMaximumProfitableGroups has the following parameter:
  • int stockPrice[n]: the stock prices Returns long integer: the number of maximum profitable groups

Constraints

  • 1 ≤ n ≤ 5 * 10⁵
  • 1 ≤ stockPrice[i] ≤ 10⁸

Example 1

Input:

stockPrice = [3, 1, 3, 5]

Output:

10

Explanation: The 10 possible groups are [3], [3, 1], [3, 1, 3], [3, 1, 3, 5], [1], [1, 3], [1, 3, 5], [3], [3, 5], [5] In each group, the maximum price is in either the first or last position.

Example 2

Input:

stockPrice = [1, 5, 2]

Output:

5

Explanation: There are 6 possible groups: [1], [1, 5], [1, 5, 2], [5], [5, 2], [2]. Only [1, 5, 2], is not maximum profitable because its maximum value 5 is not at either end of the group.

Example 3

Input:

stockPrice = [2, 3, 2]

Output:

5

Explanation: All 5 groups other than prices [2, 3, 2] are maximum profitable. In [2, 3, 2], the maximum value 3 is neither the first nor the last element. Return 5.

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

Amazon is working on a new hashing approach that takes in the original string and a seed number. Engineers decided that the seed can be generated from the same input string by counting the number of times a reverse of a substring of length k makes the new string lexicographically smaller. You are deployed with the task of developing a service that takes in a string s and an integer k, and returns the number of ways to reverse any substring of length k such that the resulting string is lexicographically smaller than the original string. Note:

    1. A substring is a contiguous sequence of characters within a string. For example, the string "zon" is a substring of "amazon", "zone", etc.but is not a substring of "zoin", "zozo", etc.
    1. A string a is lexicographically smaller than string b if `a[i] Function Description:
    1. Complete the function countNumWays in the editor.
    1. countNumWays has the following parameters:
  • a. string s:the original string
  • b. int k:the algorithm parameter Returns: int: the number of possible ways to perform the operation ensuring the given constraint

Constraints

  • `1. 2

Example 1

Input:

s = "amazon"
k = 3

Output:

1

Explanation: Consider all substrings of length k = 3. There are the possible ways to perform the given operation are showing in the above img:

Example 2

Input:

s = "ababa"
k = 2

Output:

2

Explanation: There are the possible ways for k = 2: (1) ababa --> baaba: unsuccessful, lexicographically greater thanthe original string. (2) ababa --> aabba: successfully, lexicographically smaller than the original string. (3) ababa --> abbaa: unsuccessfully, lexicographically greater. (4) ababa --> abaab: successfully, lexicographically smaller.

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

A k-Spike is an element prices[i] that has at least k strictly smaller elements to its left and at least k strictly smaller elements to its right. Given an array prices and integer k, return the count of k-Spikes.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ k ≤ n
  • 1 ≤ prices[i] ≤ 10⁹

Example 1

Input:

prices = [1, 2, 8, 5, 3, 4]
k = 2

Output:

2

Explanation: 8 at index 2 has (1, 2) to the left and (5, 3, 4) to the right that are less than 8. 5 at index 3 has (1, 2) to the left and (3, 4) to the right that are less than 5.

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

You are given a string S. In one move you can erase from S a pair of identical letters. Find the shortest possible string that can be created this way. If there are many such strings, choose the alphabetically (lexicographically) smallest one. Note that there is no limit to the number of moves. Write a function: given a string S of length N, returns the shortest string (or the first alphabetically, in the case of a draw) created by erasing pairs of identical letters from S.

Constraints

N/A (If you know about it, feel free to contact us ;D tysm!

Example 1

Input:

S = "CBCAAXA"

Output:

"BAX"

Explanation: For the input string S, you can make, for example, two moves: First, erase a pair of letters "C": "CBCAAXA" "BAAXA". Then, erase a pair of letters "A": "BAAXA" "BAX". Thus the string "BAX" is created. There is no way to create a shorter string. The other string of length 3 that can be created is "BXA", but "BAX" is the first alphabetically. The function should return "BAX".

Example 2

Input:

S = "ZYXZYZY"

Output:

"XYZ"

Explanation: First, erase a pair of letters "Y": "ZYXZYZY" "ZXZYZ". Then, erase a pair of letters "Z": "ZXZYZ" "XYZ". The other strings of length 3 that can be created are "ZYX", "YXZ", "XZY" and "ZXY", but "XYZ" is alphabetically the first, so the function should return "XYZ".

Example 3

Input:

S = "ABCBACDDAA"

Output:

" "

Explanation: For S = "ABCBACDDAA" all five pairs of identical letters can be erased. The function should return "" (empty string).

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

In an Amazon coding marathon, the following challenge was given. The uniqueness of an array of integers is defined as the number of distinct elements present. For example, the uniqueness of [1, 5, 2, 1, 3, 5] is 4, element values 1, 2, 3, and 5. For an array arr of n integers, the uniqueness values of its subarrays is generated and stored in another array, call it subarray_uniqueness for discussion. Find the median of the generated array subarray_uniqueness. Notes: The median of a list is defined as the middle value of the list when it is sorted in non-decreasing order. If there are multiple choices for median, the smaller of the two values is taken. For example, the median of [1, 5, 8] is 5, and of [2, 3, 7, 11] is 3. A subarray is a contiguous part of the array. For example, [1, 2, 3] is a subarray of [6, 1, 2, 3, 5] but [6, 2] is not. Function Description Complete the function findMedianOfSubarrayUniqueness in the editor. findMedianOfSubarrayUniqueness has the following parameter:

  • int arr[n]: the array Returns int: the median of the generated array subarray_uniqueness Constraints
  • 1 ≤ n ≤ 10⁵
  • 1 ≤ arr[i] ≤ n

Constraints

N/A

Example 1

Input:

arr = [1, 1]

Output:

1

Explanation: The subarrays along with their uniqueness values are:

  • [1]: uniqueness = 1
  • [1, 1]: uniqueness = 1
  • [1]: uniqueness = 1 subarray_uniqueness is [1, 1, 1].

Example 2

Input:

arr = [1, 2, 3]

Output:

1

Explanation: Given n = 3 and arr = [1, 2, 3], the subarrays along with their uniqueness values are:

  • [1]: uniqueness = 1
  • [1, 2]: uniqueness = 2
  • [1, 2, 3]: uniqueness = 3
  • [2]: uniqueness = 1
  • [2, 3]: uniqueness = 2
  • [3]: uniqueness = 1 subarray_uniqueness is [1, 2, 3, 1, 2, 1], and after sorting it is [1, 1, 1, 2, 2, 3].

Example 3

Input:

arr = [1, 2, 1]

Output:

1

Explanation: The subarrays with their uniqueness values are: [1]: uniqueness = 1 [1, 2]: uniqueness = 2 [1, 2, 1]: uniqueness = 2 [2]: uniqueness = 1 [2, 1]: uniqueness = 2 [1]: uniqueness = 1 The subarray_uniqueness array is [1, 2, 2, 1, 2, 1]. After sorting, the arr is [1, 1, 1, 2, 2, 2]. The choice is between the two bold values. Return the min of the two, 1. [1]: uniqueness = 1

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

Amazon Web Service has n servers, each of them either has high fault tolerance or high reliability. A system works better if all the servers have the same attributes. The inefficiency of a group of server is defined as the number of adjacent pairs of server that have different attributes. Consider, for example, a set of servers described as 1001001 where '0' means the server has high fault tolerance, '1' means the server has high reliabiity. The inefficiency of this group is 4 as described in the image below: Given a string serverType of length n consisting of '0', '1', and '?', where '0' means the server has high fault tolerance, '1' means the server has high reliability, and '?' means you can install any type of server there, find the minimum inefficiency you can get after install a server at each '?'. Function Description Complete the function findMinimumInefficiency in the editor. findMinimumInefficiency has the following parameter: string serverType: the server types Returns int: the minimum possible inefficiency 1008th thank you to spike!

Constraints

1 serverType consists of '0', '1' and '?' only

Example 1

Input:

serverType = "??011??0"

Output:

2

Explanation: In the above example, the number of servers n = 8. One optimal way to install servers is to

  1. Install a server having fault tolerance (0) at the first and the second positions.
  2. Install a server having high reliability (1) at the sixth and the seventh positions. After making these changes, the server types are '00011110'. The number of adjacent pairs having different server types is 2. It can be shown that the answer cannot be reduced from 2. Return 2. Note that another possible way to achieve a minimum number of different adjancet pairs as 2 would 00011100 and 00011000.

Example 2

Input:

serverType = "00?10??1?"

Output:

3

Explanation: One optimal way to install server is to install high-reliability servers. The new server types are "0011011111" with 3 adjacent dissimilar pairs.

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

As an aspiring developer, you are required to develop a result analysis service for a car game on Amazon games. There are n even records of d players who participated in different events in form of [race id, player's id, player's time]. For some race id, a player's ranking id decided based on the increasing order of their finish time. If two players have the same finish time, the one with a lower id is ranked lower. The average standing of any player is the average of their various positions in all the races they competed in, expressed in the form of a fraction p/q. If there are multiple possible such fractions, reduce them such that p is the minimum possible. Return a 2-dimensional array where each element i contains the ith player's p and q as described above. If the player did not compete in any races, the player's p and q values are both -1. Complete the function getAverageStanding which has the following parameters:

  • int d: the number of players
  • int records[n][3]: each record[i] contains [race id, player id, player time]

Constraints

N/A (If you know it, feel free to let us know ^^ tyvm!

Example 1

Input:

d = 3
records = [[1, 1, 100], [1, 2, 200], [2, 1, 500]]

Output:

[[-1, -1], [1, 1], [2, 1]]

Explanation: There are a total of d = 3 players.

  • Player 0 did not compete in any race, so p0 = -1 and q0 = -1.
  • Player 1 competed in 2 races and came first in both. Their average standing is (1+1)/2. Reduce as described so p1 = 1 and q1 = 1.
  • Player 2 competed in 1 race and came second. Their average standing is (2)/1. Thus, p2 = 2 and q2 = 1.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Amazon is offering a discount on every purchase of a pair of products whose price sum is divisible by x. Given the price of n products in the store, find the number of pairs (i, j) where i Function Description Complete the function getDiscountPairsin the editor.getDiscountPairs` has the following parameter(s):

    1. int x: sum of a pair of integers should be divisible by this number
    1. int prices[n]: the prices of the products Returns int: the number of pairs in the array whose sum is divisible by x

Constraints

1 ≤ x ≤ 2 * 10⁹ 1 ≤ n ≤ 10⁵ 1 ≤ prices[i] ≤ ^9

Example 1

Input:

x = 60
prices = [31, 25, 85, 29, 35]

Output:

3

Explanation: The answer is 3 based on the pairs (31, 29), (25, 35), and (85, 35). Each pair sums to a number divisible by x.

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

To attract more customers, an online retailer decides to periodically launch special promotion offers. Recently, it introduced an offer for n items in its inventory, where the i-th item grants reward[i] reward points to the customer upon purchase. Each time a customer buys an item with an offer, they receive the corresponding reward points. However, after each purchase, the reward points of all remaining items decrease by 1, unless doing so would reduce them below 0. Please help determine the maximum possible reward points that can be accumulated by making purchases in the most strategic and optimal way. Note Each item can be purchased at most once, meaning that after the i-th item is bought, its reward[i] value immediately drops to 0 and cannot be earned again. In other words, once an item is purchased, it is no longer available for future transactions. Plz complete the function in the editor by implementing the logic to maximize the total reward points collected. The function has a parameter called int[] deals, which represents the reward points of each item in the inventory. The function should return a long integer representing the maximum reward points that can be collected.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 0 ≤ deals[i] ≤ 10⁶

Example 1

Input:

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

Output:

7

Explanation: Considering 0-based indexing, the items can be purchased in the following order:

  1. First, purchase item 2, points earned = deals[2] = 2. Points of remaining items after this purchase deals = [4, 1, 0, 2, 0].
  2. Next, purchase item 3, points earned = deals[3]= 2. Points of remaining items after this purchase deals = [3, 0, 0, 0, 0].
  3. Finally, purchase item 0, points earned = deals[0] = 3. Points of remainig items after this purchase deals = [0, 0, 0, 0, 0] At this point, no items have reward points left. The maximum earning points is 2 + 2 + 3 = 7.

Example 2

Input:

deals = [5 ,5 ,5]

Output:

12

Explanation: Using 0-based indexing, the items can be purchased in the following order:

  1. First, purchase item 0, points earned = deals[0] = 5. Points of remaining items after this purchase deals = [0, 4, 4].
  2. Next, purchase item 1, points earned to = deals[1] = 4. and deals = [0, 0, 3].
  3. Finally, purchase item 2, points earned = deals[2] = 3 and deals = [0, 0, 0]. The maximum earning reward points is (5 + 4 + 3 = 12).
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Amazon Academy recently organized a scholaship test on its platform. There are nstudents with roll numbers 1, 2, ..., n who appeared for the test, where the rank secured by the ithstudent is denoted by rank[i]. Thus, the array rank is a permutation of length n. Groups can only be formed with students having consecutive roll numbers, in other words, a subarray of the original array. For each value `x (1 Notes

    1. The mean value of an array of kelements is defined as the sum of elements divided by k.
    1. A permutation of leangth nis a sequence where each number from qtonappears exactly once.
    1. A subarray of an array is a contiguous section of the array. Function Description Complete the function getMeanRankCount in the editor. getMeanRankCount has the following parameter: int rank[n]: the ranks of the students. Returns int[n]: the ith integer (where 1 ≤ i ≤ n).

Constraints

  • 1 ≤ n ≤ 10³
  • 1 ≤ rank[i] ≤ n
  • The array rank contains all distinct elemens, and thus, is a permutation of {1..n}.

Example 1

Input:

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

Output:

[1, 2, 3, 2, 1]

Explanation: Read the above as 'For the mean x = 1, the group [1] has mean value 1. There is 1 group'. and so on. The full answer is [1, 2, 3, 2, 1].

Example 2

Input:

rank = [4, 3, 2, 1]

Output:

[1, 2, 2, 1]

Explanation:

  • x = 1 -> [1]
  • x = 2 -> [3, 2, 1], [2]
  • x = 3 -> [3], [4, 3, 2]
  • x = 4 -> [4]

Example 3

Input:

rank = [4, 7, 3, 6, 5, 2, 1]

Output:

[1, 1, 1, 4, 4, 1, 1]

Explanation:

  • x = 1 -> [1]
  • x = 2 -> [2]
  • x = 3 -> [3]
  • x = 4 -> [4], [3, 6, 5, 2], [7, 3, 6, 5, 2, 1], [4, 7, 3, 6, 5, 2 ,1]
  • x = 5 -> [5], [7, 3], [4, 7, 3, 6] and [4, 7, 3, 6, 5]
  • x = 6 -> [6]
  • x = 7 -> [7]
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

enthusiasts at Amazon are working on a data interpolation model to increase the size of the data set for better learning. In one such model, there are 26 different classifications possible and the i^th data point is annotated to belong to the data[i] class where data is a string of lowercase English letters. However, for some data points, data[i] is equal to '?' representing that the corresponding data point classification is missing and needs to be replaced with some lowercase English letter. The cost of any index i of the string data is defined as the number of indices before it that also have the same classification result. For example, For the string "hello" the costs are [0, 0, 0, 1, 0] corresponding to each index.

  • For the string "abc" the costs are [0, 0, 0] corresponding to each index.
  • For the string "aaccbbc" the costs are [0, 1, 0, 1, 0, 1, 2] corresponding to each index because before the last c character, there are 2 more c characters. The task is to replace all the characters '?' so that the sum of the indices' cost is minimum. Given the string data, interpolate the data such that the total cost of all the indices is minimized. If there are multiple ways to get minimum cost, print the lexicographically smallest possible string that satisfies the goal. Function Description Complete the function getMinCostData in the editor below. getMinCostData has the following parameter:
  • data: a string Returns string: the lexicographically minimum string with the minimum cost Note: A string p is lexicographically smaller than string q, if p is a prefix of q, is not equal to q, or there exists i, such that p_i j. Note that while comparing p_j and q_j we consider their ASCII values, i.e. '[' and ']' are greater than any uppercase English letters. For example, "ABC" is lexicographically smaller than "BCD" and "ABCD" but larger than "AAC" and "AACDE".

Constraints

  • 1 ≤ |data| ≤ 10⁵
  • It is guaranteed that s contains at least one character '?' and others are lowercase English letters or the character '?'.

Example 1

Input:

data = "aaaa?aaaa"

Output:

"aaaabaaaa"

Explanation: Putting 'b' does not contribute to the total cost and is lexicographically minimum.

Example 2

Input:

data = "??????"

Output:

"abcdef"

Explanation: This is the lexicographically smallest string that keeps the cost least. The cost will be 0 as there will be no duplicate character present in it.

Example 3

Input:

data = "abcd?"

Output:

"abcde"

Explanation: Some of the possible replacements are shown below: The strings "abcda", "abcdb", "abcdc", and "abcdd" cost 1 because the last element has a duplicate character. We can see that the minimum cost possible is 0. Since there can be multiple possible strings with 0 cost, we choose the lexicographically smaller one i.e. abcde.

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

In Amazon Go Store, there are nitems, each associated with two positive values a[i] and b[i]. There are infinitely many items of each type numbered from 1 to infinity and the item numbered j of type i costs a[i] + (j - 1) * b[i] units. Determine the minimum possible cost to purchase exactly m items. Function Description Complete the function getMinimumCost in the editor. getMinimumCost has the following parameters:

    1. int a[n]: an array of integers
    1. int b[n]: an array of integers
    1. m: the number of items to purchase Returns long integer: the minimum cost

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ a[i], b[i] ≤ 10⁵
  • 1 ≤ m ≤ 10⁵

Example 1

Input:

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

Output:

7

Explanation: The optimal types to buy are-

  1. Choose i = 1. This is the first purchase of this type of item, so j = 1. The first item costs a[1] + (1 - 1) * b[i] = 1 + (1 - 1) * 2 = 1.
  2. Choose i = 2. Again, it is the first purchase of this type so j = 1. The second item costs 1 + (1 - 1) * 3 = 1.
  3. Choose i = 0 which costs 2 + (1 - 1) * 1 = 2.
  4. When a second unit of any type is purchased, j = 2 for that transaction. The costs of a second units of each item are: a. a[0] costs a[0] + (2 - 1) * b[0] = 2 + 11 = 3 b. a[1] costs 1 + 12 = 3 c. a[2] costs 1 + 1*3 = 4 d. Choose either a[0] or a[1] since they cost less. The total cost to purchase is 1 + 1 + 2 + 3 = 7.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Breaking! Amazon has recently introduced an exciting new game called Let's Play Crush Fruit Together! In this game, players can select any two distinct types of fruits and crush them together. Each fruit type is represented as a unique integer within an array. Your task is to determine the minimum possible number of fruits remaining after repeatedly performing this operation. That means, as long as there exist at least two different fruit types in the array, you can keep picking and removing them. Function Description Complete the function getMinimumFruits in the editor. getMinimumFruits has the following parameter(s): int fruitsArray[n]: an array of n integers where each integer represents a specific type of fruit. Returns The function should return a single integer, which represents the smallest number of fruits left in the array after performing the "crush operation" as many times as possible.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ fruitsArray[i] ≤ 10⁹

Example 1

Input:

fruitsArray = [3, 3, 1, 1, 2]

Output:

1

Explanation: We can first crush fruit type 1 (e.g., banana) with fruit type 2 (e.g., pineapple). Next, we crush the remaining fruit type 1 (banana) with one fruit type 3 (orange). Now, only one fruit type 3 (orange) remains in the array. Since there are no distinct fruit types left to crush, the minimum number of remaining fruits is 1.

Example 2

Input:

fruitsArray = [1, 2, 5, 6]

Output:

0

Explanation: We can first crush fruit type 1 with fruit type 2. Next, we can crush fruit type 5 with fruit type 6. Since all fruit types have been successfully removed through crushing, the final number of fruits left is 0.

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

There are 2 arrays which denote departing and returning flights with the respective indexes being time and the values of the array being the cost it takes for the flight. Return the minimum cost for a round trip provided the return flight can only be taken at a time post departing flight time (i.e if departing at time i, one can catch a returning flight only from time (i+1) onwards). Function Description Complete the function getMinimumRoundTripCost in the editor. getMinimumRoundTripCost has the following parameters:

    1. int[] departing: an array of integers representing the cost of departing flights
    1. int[] returning: an array of integers representing the cost of returning flights Returns int: the minimum cost for a round trip

Example 1

Input:

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

Output:

2

Explanation: The minimum cost for a round trip can be obtained by taking the departing flight at time 0 with cost departing[0] = 1 and the returning flight at time 3 with cost returning[3] = 1. The total minimum cost is 1 + 1 = 2.

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

Several processes are scheduled for execution on an AWS server. On one server, n processes are schedule where the i^th process is assigned a priority of priority[i]. The processes are placed sequentially in a queue and are numbered 1, 2,..,n. The server schedules the processes per the following algorithm:

  1. It finds the maximum priority shared by at least 2 processes. Let that be denoted by p. (if there is no such priority or p = 0, the algorithm is terminated)
  2. Otherwise, select the two of the processes with the lowest indexes and priority p, call them process1 and process2.
  3. The server executes process1 and removes it from the queue.
  4. To avoid starvation, it reduces the priority of process2 to floor(p/2).
  5. Start again from step 1. Given the initial priority of the processes, find the final priority of the processes which remain after the algorithm terminates. Note that relative the arrangement of remaining processes in the queue remains the same,only their priorities change. Function Description Complete the function getPrioritiesAfterExecution in the editor. getPrioritiesAfterExecution has the following parameter:
  • int priority[n]: the initial prorities of processes Returns
  • int[]: the final priorities of the remaining processes

Constraints

  • 1. 1 ≤ n ≤ 10⁵
  • 2. 1 ≤ priorities[i] ≤ 10⁹

Example 1

Input:

priority = [6, 6, 6, 1, 2, 2]

Output:

[3, 6, 0]

Explanation: The scheduler works as follows:

  1. p = 6 at indices 1, 2 and 3. The indices used are process1 = 1, process2 = 2. Remove process 1 and update the priority of process 2 to floor(6/2) = 3.
  2. p = 2 and process1 = 4, process2 = 5. So, update the priority = floor(2/2) = 1 of process2 and remove process1. Current set of process priorities, priority = [3, 6, 1, 1].
  3. p = 1 and process 1 = 3, process2 = 4. So, update the priority = floor(1/2) = 0 of process2 and remove process1. Current set of process priorities, priority = [3, 6, 0].
  4. There are no more matching process priorities so the algorithm ends. The final priorities of the reamining processes are priority = [3, 6, 0].

Example 2

Input:

priority = [4, 4, 2, 1]

Output:

[0]

Explanation: p = 4 and process1 = 1, process2 = 2. So, update the priority = floor(4/2) = 2 of process2 and remove process1. Current set of process priorities, priority = [2, 1, 1]. p = 2 and process1 = 1, process2 = 2. So, update the priority = floor(2/2) = 1 of process2 and remove process1. Current set of process priorities, priority = [1, 1]. p = 1 and process1 = 1, process2 = 2. So, update the priority = floor(1/2) = 0 of process2 and remove process1. Current set of process priorities, priority = [0].

Example 3

Input:

priority = [2, 1, 5, 10, 10, 1]

Output:

[0, 1]

Explanation: p = 10 and process1 = 4, process2 = 5. So, update the priority = floor(10/2) = 5 of process2 and remove process1. Current set of process priorities, priority = [2, 1, 5, 5, 17]. p = 5 and process1 = 3, process2 = 4. So, update the priority = floor(5/2) = 2 of process2 and remove process1. Current set of process priorities, priority = [2, 1, 2, 17]. p = 2 and process1 = 1, process2 = 3. So, update the priority = floor(2/2) = 1 of process2 and remove process1. Current set of process priorities, priority = [1, 1, 17]. p = 1 and process1 = 1, process2 = 2. So, update the priority = floor(1/2) = 0 of process2 and remove process1. Current set of process priorities, priority = [0, 1].

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

The developers of Amazon are working on a prototype for a simple load-balancing algorithm. There are num_servers servers numbered from 0 to num_servers - 1 and the initial number of requests assigned to each server is 0. In the i-th second, a request comes from IP hash of requests[i], and it must be assigned to the server with the minimum number of requests amongst the first requests[i] servers. For example, if requests[i] = 4, the request must be assigned to the server with the minimum number of requests amongst the servers with id [0, 1, 2, 3]. If there are multiple servers with the same minimum number of requests, choose the one with the minimum id. When a request is assigned to a server, its number of requests increases by 1. Given num_servers and the array requests, for each request, find the id of the server it is assigned to. Function Description Complete the function getServerId in the editor. getServerId takes the following arguments:

  • int num_servers: the number of servers
  • int requests[n]: the sizes of the requests Returns int[n]: the ids of the servers each request is assigned to Thanks a bajillion, spike!

Constraints

  • 1 ≤ num_servers ≤ 10⁵
  • `0 ≤ requests[i]

Example 1

Input:

num_servers = 5
requests = [3, 2, 3, 2, 4]

Output:

[0, 1, 2, 0, 3]

Explanation: The requests are processed as follows: Hence the answer is [0, 1, 2, 0, 3].

Example 2

Input:

num_servers = 5
requests = [4, 0, 2, 2]

Output:

[0, 0, 1, 1]

Explanation: After the first request, the number of requests is [1, 0, 0, 0, 0]. After the second request, the number of requests is [2, 0, 0, 0, 0]. After the third request, the number of requests is [2, 1, 0, 0, 0]. After the fourth request, the number of requests is [2, 1, 1, 0, 0].

Example 3

Input:

num_servers = 5
requests = [0, 1, 2, 3]

Output:

[0, 0, 1, 2]

Explanation: Each request is assigned to the first index with the number of requests equal to 0.

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

The developers of Amazon are working on a prototype for a simple load-balancing algorithm. There are num_servers servers numbered from 0 to num_servers - 1 and the initial number of requests assigned to each server is 0. In the i-th second, a request comes from IP hash of requests[i], and it must be assigned to the server with the minimum number of requests amongst the first requests[i] servers. For example, if requests[i] = 4, the request must be assigned to the server with the minimum number of requests amongst the servers with id [0, 1, 2, 3]. If there are multiple servers with the same minimum number of requests, choose the one with the minimum id. When a request is assigned to a server, its number of requests increases by 1. Given num_servers and the array requests, for each request, find the id of the server it is assigned to. Function Description Complete the function getServerIds in the editor. getServerIds takes the following arguments:

  • int num_servers ; the number of servers
  • int requests[] ; the sizes of the requests Returns int[] ; the ids of the servers each request is assigned to

Constraints

  • 1 ≤ num_servers ≤ 10⁵
  • `0 ≤ requests[i]

Example 1

Input:

num_servers = 5
requests = [4, 0, 2, 2]

Output:

[0, 0, 1, 1]

Explanation: After the first request, the number of requests is [1, 0, 0, 0, 0]. After the second request, the number of requests is [2, 0, 0, 0, 0]. After the third request, the number of requests is [2, 1, 0, 0, 0]. After the fourth request, the number of requests is [2, 1, 1, 0, 0].

Example 2

Input:

num_servers = 5
requests = [0, 1, 2, 3]

Output:

[0, 0, 1, 2]

Explanation: Each request is assigned to the first index with the number of requests equal to 0.

Example 3

Input:

num_servers = 5
requests = [3, 2, 3, 2, 4]

Output:

[0, 1, 2, 0, 3]

Explanation: The requests are processed as follows: Thus, the answer is [0, 1, 2, 0, 3] :)

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

Amazon Prime Video has recently released an exclusive series on its platform. They collected the number of viewers from n different regions across the world and stored the data in the array num_viewers. The success value of the release is defined as the sum of viewership in the top k regions, those with the highest viewers. For example, if num_viewers = [3, 2, 1, 4, 5] and k = 3, then the success value of the release is 3 + 4 + 5 = 12 as [3, 4, 5] are the top 3 values. Given a number of k values, calculate the success value for each query. Function Description Complete the function getSuccessValue in the editor. getSuccessValue has the following parameters: int num_viewers[n]: viewership from n different regions int queries[q]: an array of k values Returns int[q]: the maximum possible success values for each query

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ q ≤ 10⁵
  • 1 ≤ num_viewers[i] ≤ 10⁹
  • 1 ≤ queries[i] ≤ n

Example 1

Input:

num_viewers = [2, 5, 6, 3, 5]
queries = [2, 3, 5]

Output:

[11, 16, 21]

Explanation: The viewership in 5 regions is num_viewers = [2, 5, 6, 3, 5], and we want to find the success value for 3 queries that are queries = [2, 3, 5]. For the first query, k = 2, the viewership of the top 2 regions is [6, 5]. The success value is 6 + 5 = 11. For the second query, k = 3, the viewership of the top 3 regions is [6, 5, 5] and 6 + 5 + 5 = 16. For the third query, k = 5, all the 5 regions are used for the success value and 6 + 5 + 5 + 3 + 2 = 21. Return [11, 16, 21].

Example 2

Input:

num_viewers = [7, 3, 5, 2]
queries = [1, 4]

Output:

[7, 17]

Explanation: For the first query, k = 1, only the top region is used for the success value. For the second query, k = 4, all 4 regions are used. Return [7, 17].

Example 3

Input:

num_viewers = [7, 5, 6]
queries = [1, 2, 3]

Output:

[7, 13, 18]

Explanation: For the first query, k = 1, only the top region is used for the success value. For the second query, k = 2, only the top 2 regions are used. For the third query, k = 3, all 3 regions are used. Return [7, 13, 18].

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

Amazon Warehouse delivers different items in different trucks having varied capacities. Given an array, trucks, of n integers that represents the capacities of different trucks, and an array, items, of m integers that represent the weights of different items, for each item, find the index of the smallest truck which has a capacity greater than the item's weight. If there are multiple such trucks, choose the one with the minimum index. If there is no truck that can carry the item, report -1 as the answer for the corresponding item. Note: Assume that the trucks are indexed starting from 0. Also, multiple items can be mapped to the same truck. Each item is mapped independently, hence the trucks do not lose any capacity when a particular item is mapped to it. Function Description Complete the function getTrucksForItems in the editor below. getTrucksForItems has the following parameters:

  • int trucks[n]: the capacities of the trucks
  • int items[m]: the weights of the items

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ trucks[i] ≤ 10⁹
  • 1 ≤ m ≤ 10⁵
  • 1 ≤ items[m] ≤ 10⁹

Example 1

Input:

trucks = [4, 5, 7, 2]
items = [1, 2, 5]

Output:

[3, 0, 2]

Explanation: Given the above trucks and items, they can be mapped as the image shows. The smallest truck that can carry the third weight, 5, is truck 2 with a capacity of 7. Similar logic is applied to the other elements and the answer is [3, 0, 2].

Example 2

Input:

trucks = [5, 3, 8, 1]
items = [6, 10]

Output:

[2, -1]

Example 3

Input:

trucks = [1, 3, 5, 2, 3, 2]
items = [1, 2, 3]

Output:

[3, 1, 2]

Explanation:

  1. items[0] = 1, 2 is the samllest value in the array greater than 1. trucks[3] and trucks[5] are equal to 2. The minimum index among them is 3.
  2. items[1] = 2, 3 is the smallest value in the array greater than 2. trucks [1] and trucks[4] are equal to 3. The minimum index among them is 1.
  3. items[2] = 3, 5 is the smallest value in the array greater than 3. trucks[2] is equal to 5.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

X stores its data on different servers at different locations. From time to time, due to several factors, X needs to move its data from one location to another. This challenge involved keeping track of the locations of X's data and report them at the end of the year. At the start of the year, X's data was located at n different locations. Over the course of the year, X's data was moved from one server to another m times. Precisely, in the ith operation, the data was moved from movedFrom[i] to movedTo[i]. Find the locations of the data after all m moving operations. Return the locations in ascending order. Note: It is guaranteed that for any movement of data : There is data at movedFrom[i]. There is no data at movedTo[i]. Returns int[]: the locations storing data after all moves are made, in ascending order.

Constraints

N/A (If you know about it, feel free to contact us. THX!

Example 1

Input:

locations = [1, 7, 6, 8]
movedFrom = [1, 7, 2]
movedTo = [2, 9, 5]

Output:

[5, 6, 8, 9]

Explanation: Data begins at locations listed in locations. Over the course of the year, the data was moved three times. Data was first moved from movedFrom[0] to movedTo[0], from 1 to 2. Next, it is moved from 7 to 9, and finally from location 2 to 5. In the end, the locations where data is present are [5,6,8,9] in ascending order.

Example 2

Input:

locations = [1, 5, 2, 6]
movedFrom = [1, 4, 5, 7]
movedTo = [4, 7, 1, 3]

Output:

[1, 2, 3, 6]

Explanation: (ignore the typo in the img) The operations should be in order. For example, 5 is in the output because the 1st operation moved data from 1->2. Then in the following operation (3rd), the data is moved from 2->5

Example 3

Input:

locations = [1, 2, 3]
movedFrom = [1, 2]
movedTo = [5, 6]

Output:

[3, 5, 6]

Explanation: N/A (This example is a sample test case :)

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

Given an array arr of n integers, in a single operation, one can reduce any element of the array by 1. Find the minimum number of operations required to make the array a bitonic* array.

  • A bitonic array can have any number of zeros in prefix and suffix. The non-zero part should increase from 1 to some integer k and then decrease to 1. Example of a bitonic array: [0,1,2,3,2,1,0,0].

Constraints

N/A

Example 1

Input:

arr = [3,3,3,3,3]

Output:

6

Explanation: Answer: 6 (Final Array: [1,2,3,2,1])

Example 2

Input:

arr = [1,1,3,1,1]

Output:

3

Explanation: Answer: 3 (Final Array: [0,1,2,1,0])

Example 3

Input:

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

Output:

5

Explanation: Answer: 5 (Final Array: [1,2,1,0,0] or [0,0,1,2,1])

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

Amazon.com is distributing coupons in the form of a lottery system for loyal customers. The coupons are called "lucky numbers" and the customer with the largest lucky number gets the best discount. Devise a method to determine the maximum possible lucky number. A positive integer is a lucky number if its decimal representation contains only digits x and y. For example, if x=2 and y=5, then 2, 552, and 5225 are lucky numbers, and 3, 24, 57 and 389 are not. For example, if x=2 and y=5, then 2, 552, and 5225 are lucky numbers, and 3, 24, 57 and 389 are not. Given two different digits x and y and a positive integer n, determine the maximum possible lucky number, the sum of whose digits is n. It is guaranteed that at least one lucky number exists for the given x, y, and n. Function Description Complete the function getMaxLuckyNumber in the editor. getMaxLuckyNumber has the following parameters:

  • x: an integer
  • y: an integer
  • n: the sum of the digits of the lucky number Returns int: the maximum possible lucky number

Constraints

N/A

Example 1

Input:

x = 3
y = 4
n = 13

Output:

4333

Explanation: If the two digits that make up the number are x = 3 and y = 4, and the sum of the digits must be n = 13, then the lucky numbers are:

  • 3334
  • 3343
  • 3433
  • 4333 The maximum lucky number is 4333.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are shopping on Amazon.com for some bags of rice. Each listing displays the number of grains of rice that the bag contains. You want to buy a perfect set of rice bags. From the entire search results list, riceBags. A perfect set of rice bags, perfect, is defined as: The set contains at least two bags of rice. When the rice bags in the set perfect are sorted in increasing order by grain count, it satisfies the condition perfect[i] * perfect[i] = perfect[i+1] for all 1 ≤ i Function Description Complete the function maxSetSizein the editor.maxSetSize` has the following parameter:

  • int riceBags[n]: the list of bags of rice by rice grain counts Returns int: the size of the largest set possible or -1 if there is none

Constraints

1 ≤ n ≤ 2 × 10⁵² ≤ riceBags[i] ≤ 10⁶

Example 1

Input:

riceBags = [625, 4, 2, 5, 25]

Output:

3

Explanation: All of the possible perfect sets:

  • [625, 25]
  • [4, 2]
  • [5, 25]
  • [625, 5, 25] The largest perfect set has size 3.

Example 2

Input:

riceBags = [3, 9, 4, 2, 16]

Output:

3

Explanation: Let the bags of rice available on Amazon have grain counts [3, 9, 4, 2, 16]. The following are the perfect sets: Set perfect = [3, 9]. The size of this set is 2. Set perfect = [4, 2]. The size of this set is 2. Set perfect = [4, 16]. The size of this set is 2. Set perfect = [4, 2, 16]. The size of this set is 3. The size of the largest set is 3. The image above illustrates the correct ordering of the purchased rice bags by grains of rice.

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

Given a sequence of n natural numbers a_1, a_2, ..., a_n, you are to assign a sign (+ or -) to each a_i such that the cumulative sum of the signed a_1 + a_2 + ... + a_i remains positive for each i in 1 Input The input consists of a single line containing nnatural numbers separated by spaces, representing the sequencea_1, a_2, ..., a_n. **Output** Output a single integer, the maximum number of negative signs that can be assigned to the elements of the sequence, while ensuring that all partial cumulative sums a_1 + a_2 + ... + a_i` are positive.

Constraints

  • 1 ≤ n ≤ 100000
  • 1 ≤ a_i ≤ 10⁹

Example 1

Input:

sequence = [3, 2, 1, 1, 1, 1]

Output:

4

Explanation: In the given example, an optimal way to assign the signs could be: +3 +2 -1 -1 -1 -1. This assignment keeps all prefix sums positive, while still maximizing the number of negative signs.

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

You are given a string S, consisting of lowercase Latin letters and/or question marks (?), your goal is to replace each question mark with any lowercase Latin letter (from 'a' to 'z') in such a way that the length of the longest repeated substring is maximized.

  • A repeated substring is a segment/substring of even length within the string where the first half is identical to the second half.
  • A substring is any contiguous portion of the string. Objective: Replace each question mark in the string S with lowercase Latin letters to create the longest possible repeated substring. Input Format The only line of input contains a string S, consisting only of lowercase Latin letters and/or question marks. Output Format Print a single integer, the maximum length of the longest repeated substring as you replace each question mark in the string with some lowercase Latin letter.

Example 1

Input:

s = "a??a"

Output:

4

Explanation: :)

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

An array is given. In one operation, you can delete one element and then add the elements which are present to the left and right of it. You can also delete elements which are present at index 0 and the last index. Perform this operation until only one element is left. The goal is to perform the operations in such a way that you get the maximum element as the answer.

Constraints

  • The size of the array could be up to 10⁵.
  • `-10⁹

Example 1

Input:

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

Output:

4

Explanation: Let's say we remove -2 at index 3, then the array would be [-2, 4, 2] (adding elements present at index 2 and 4). Now, removing the element from index 0, the array would be [4, 2]. Now, removing the element from index 1, the array would be [4]. The final answer is 4. So basically, repeat this operation until only one element is left. That would be your answer. Perform these operations in such a way that you get the maximum element as the answer.

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

Given a string s consisting of parentheses, you need to find the maximum score possible in a balanced substring of s. The score of a substring is calculated by choosing two indices i and `j (0 Note The input string s will only consist of opening and closing parentheses. A balanced substring is a substring that has an equal number of opening and closing parentheses.

Constraints

N/A (feel free to contact us if you know about it. TYSM!

Example 1

Input:

s = "(())"

Output:

4

Explanation: There are two possible balanced substrings: "( ( ) )" (3-0) + (2-1) = 4 or (2-0) + (3-1) = 4

Example 2

Input:

s = "()()"

Output:

3

Explanation: We dont need to use the two parenthesis in the middle :) Updated on 02-04-2025, relative image will be uploaded next time :P

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

One of the products listed on Amazon Ecommerce is available in n sizes as indicated in the array size. The category manager recognizes that some of the sizes are repetitive and do not provide a good user experience. To make the best use of inventory, the product should be available in distinct sizes. The size of the i-th product, size[i], can be increased by one unit for an amount in the cost array, cost[i]. Given the arrays size and cost for the product, find the minimal total cost in order to make all the sizes distinct. Function Description Complete the function minimalCostToIncreasePackageSize in the editor. minimalCostToIncreasePackageSize has the following parameters:

    1. int size[n]: an array of integers representing the sizes
    1. int cost[n]: an array of integers representing the cost to increase each size Returns int: the minimal total cost to make all the sizes distinct

Example 1

Input:

size = [2, 3, 2, 2]
cost = [2, 4, 5, 1]

Output:

7

Explanation: It costs 7 units to make the prices distinct. We can also adjust size[1] to 5, which costs cost[1] * (5 - size[1]) = 8, and size[3] to 4, which costs cost[3] * (4 - size[3]) = 2. Therefore, the total cost is 8 + 2 = 10. However, 7 is the minimum cost required to make all sizes distinct.

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

Amazon Prime Video has movies in category 'comedy' or 'drama'. Determine the earliest time you can finish at least one movie from each category. The release schedule and duration of the movies are provided.

  • You can start watching a movie at the time it is release or later.
  • If you begin a movie at time t, it ends at t + duration.
  • If a movie ends at time t + duration , the second movie can start at that time, t+ duration, or later.
  • The movies can be watched in any order. Complete the function minimumTimeSpent which has the following parameters:
  • int comedyReleaseTime[n]: release times
  • int comedyDuration[n]: durations
  • int dramaReleaseTime[m]: release times
  • int dramaDuration[m]: durations

Constraints

  • 1 ≤ n, m ≤ 10⁵
  • 1 ≤ comedyReleaseTime[i], comedyDuration[i], dramaReleaseTime[i], dramaDuration[i] ≤ 10⁶

Example 1

Input:

comedyReleaseTime = [1, 4]
comedyDuration = [3, 2]
dramaReleaseTime = [5, 2]
dramaDuration = [2, 2]

Output:

6

Explanation: Duration and release time are aligned by index. Two of the best ways to finish watching one movie from each category at the earliest time are as follows:

  • Start watching comedy movie1 at time t = 1 and until t = 1 + 3 = 4. Then, watch the drama movie1 from time t = 4 to t = 4 + 2 = 6.
  • Start watching a comedy movie2 at time t = 2 and until t = 2 + 2 = 4. Then, watch the drama movie1 from time t = 4 to t = 4 + 2 = 6. The earliest finish time and also answer is 6. Examples that are sub-optimal include:
  • Start watching a comedy movie2 at time t = 4 and until t = 4 + 2 = 6. Then, watch the drama movie1 from time t = 6 to t = 6 + 2 = 8.
  • Start watching a comedy movie1 at time t = 1 and until t = 1 + 3 = 4. Then, watch the drama movie1 from time t = 5 to t = 5 + 2 = 7.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Have the function MathChallenge take str which will be a string representing a polynomial containing only (+/-) integers, a letter, parenthesis, and the symbol "^" and return it in expanded form. For example: if str is "(2x²+4)(6x³+3)", then the output should be "12x⁵+24x³+6x²+12". Both the input and output should contain no spaces. The input will only contain one letter, such as "x", "y", "b", etc. There will only be four parenthesis in the input and your output should contain no parenthesis. The output should be returned with the highest exponential element first down to the lowest. More generally, the form of str will be: (+/-)[num][(letter)(^)(+/-)[num]]...[(+/-)[num]]...)(copy) where '[]' represents optional features, '{}' represents mandatory features, 'num' represents integers and "letter" represents letters such as "x".

Example 1

Input:

str = "(1x)(2x⁻²+1)"

Output:

x+2x⁻¹

Explanation: ~

Example 2

Input:

str = "(-1x³)(3x³+2)"

Output:

-3x⁶-2x³

Explanation: ..

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

In a bustling warehouse of Amazon, a dedicated caretaker oversees a collection of n piles of boxes, each containing a different number of goods waiting to be shipped. To ensure that the treasures are evenly distributed, the caretaker is allowed to perform a magical operation: they can choose any two distinct piles, i and j, as long as pile i has at least one box. With a gentle flick of their wrist, they can move a box from pile i to pile j, thereby balancing the wealth between the two. The caretaker's quest is to minimize the difference between the pile with the most boxes and the one with the fewest. This difference is known as d, and the caretaker seeks to find the least number of operations required to achieve this fair distribution of boxes. Your task is to complete the function findMinimumOperations, which will reveal the minimum operations needed to attain this harmony.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ boxes[i] ≤ 10⁹

Example 1

Input:

boxes = [5, 5, 8, 7]

Output:

2

Explanation: Consider the number of piles to be n = 4 and the boxes in them are boxes = [5, 5, 8, 7]. The minimum possible difference that can be achieved is 1 by transforming the piles into [6, 6, 7, 6] as below. Hence the answer is 2.

Example 2

Input:

boxes = [2, 4, 1]

Output:

1

Explanation: Move a box from pile 2 to pile 3: [2, 4, 1] -> [2, 3, 2]

Example 3

Input:

boxes = [4, 4, 4, 4, 4]

Output:

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

解锁全部 388 道题的解法

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

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

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