Amazon OA
Amazon OA
Problem Description
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 ith 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.
Examples
Consider the following conceptual examples for selecting primary and backup servers:
●
In the second configuration, the system memory capacity is memory[serverA] +
Note: The problem statement specifies that a system always contains an even number of
servers. Example 2 (Sample Case 1) uses n=3, which is an odd number. This might be a
discrepancy in the problem description or an edge case to consider.
Constraints
● 2 ≤ n ≤ 2 * 10^5
● 1 ≤ memory[i] ≤ 10^9
Sol:
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
●
long long total_capacity = 0;
if (memory_count % 2 == 0) {
for (int i = 0; i < memory_count; i += 2) {
total_capacity += memory[i];
}
} else {
for (int i = 1; i < memory_count; i += 2) {
total_capacity += memory[i];
}
}
return total_capacity;
}
Find the minimum amount needed to purchase items whose combined weight is at least
minWeight. Multiple units of an item can be purchased.
Example
n = 5
cost = [2, 5, 7, 11, 25]
minWeight = 26
●
The answer is 37, representing the minimum cost to achieve the weight requirement.
Function Description
Complete the function getMinimunCost in the editor with the following parameters:
Returns
Examples
Example 1:
Input:
5
4
3
2
1
10
2
Output:
1
Explanation: It is optimal to buy 1 unit of item 3 which has a weight of 23 = 8 units (greater
Example 2:
Input:
4
10
9
8
10
14
Output:
20
●
Explanation: It is optimal to buy 2 units of item 0 (0-based), which weighs 8 units. Total
combined weight = 2 * 8 = 16, which is greater than minWeight. Total cost = 2 * 10
= 20.
Constraints
● 1 <= n <= 30
● 1 <= cost[i] <= 109
● 1 <= minWeight <= 109
Sol:
#include <vector>
#include <queue>
#include <unordered_set>
#include <algorithm>
std::vector<std::unordered_set<int>> adj(tree_nodes);
for (size_t i = 0; i < tree_from.size(); ++i) {
adj[tree_from[i]].insert(tree_to[i]);
adj[tree_to[i]].insert(tree_from[i]);
}
while (!q.empty()) {
int u = q.front();
q.pop();
remaining_nodes--;
if (adj[u].empty()) continue;
int v = *adj[u].begin();
●
adj[u].clear();
adj[v].erase(u);
if (remaining_nodes <= 2) {
return 0;
}
if (leaves.empty()) {
break;
}
remaining_nodes -= leaves.size();
while(!leaves.empty()){
int u = leaves.front();
leaves.pop();
if (adj[u].empty()) continue;
int v = *adj[u].begin();
adj[u].clear();
adj[v].erase(u);
}
}
if (remaining_nodes <= 1) {
return 0;
}
●
Collect The Coins
Problem Description
Alex is playing a game in Hackerland and needs to collect coins from various locations. The
city is represented as a tree with n vertices labeled from 0 to n - 1. There is an array called
coins of size n, where coins[i] is either 0 or 1, where 1 means the vertex contains a coin.
Alex must travel the tree's edges to collect all the coins. The distance between two vertices
is the number of edges between them. From any given vertex x, Alex can collect all coins
located within a distance of 2 edges from x.
The goal is to find the shortest path that allows Alex to collect all the coins. Alex can choose
any vertex, but must start and end at that vertex. The path can traverse the same edge
multiple times, and all edges are bidirectional.
Return the number of edges in the shortest path along which Alex can collect all the coins.
Returns:
●
int: the number of edges in the shortest path.
Examples
Example 1:
Input:
tree_nodes = 12
coins = [1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1]
tree_from = [0, 0, 1, 2, 3, 4, 5, 6, 8, 9, 10]
tree_to = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Output: 10
Explanation: One optimum path is to start at vertex 3 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 6 -> 4 ->
3 -> 9 -> 11. Collect coins from vertices 2 (coins at 0, 2 and 3), 6 (coins at 6 and 8), and 9
(coin at vertex 11).
Example 2:
Input:
tree_nodes = 10
coins = [1, 0, 1, 1, 1, 0, 0, 0, 1, 1]
tree_from = [0, 0, 0, 0, 1, 6, 7, 8]
tree_to = [1, 2, 3, 4, 5, 7, 8, 9]
Output: 4
Constraints
● 2 <= tree_nodes <= 10^5
● coins[i] = 0 or coins[i] = 1, where 0 <= i < tree_nodes
● 0 <= tree_from[i] < tree_nodes where 0 <= i < tree_nodes - 1
● 0 <= tree_to[i] < tree_nodes where 0 <= i < tree_nodes - 1
Sol:
#include <vector>
#include <queue>
#include <unordered_set>
#include <algorithm>
●
std::vector<std::unordered_set<int>> adj(tree_nodes);
for (size_t i = 0; i < tree_from.size(); ++i) {
adj[tree_from[i]].insert(tree_to[i]);
adj[tree_to[i]].insert(tree_from[i]);
}
while (!q.empty()) {
int u = q.front();
q.pop();
remaining_nodes--;
if (adj[u].empty()) continue;
int v = *adj[u].begin();
adj[u].clear();
adj[v].erase(u);
if (remaining_nodes <= 2) {
return 0;
}
if (leaves.empty()) {
●
break;
}
remaining_nodes -= leaves.size();
while(!leaves.empty()){
int u = leaves.front();
leaves.pop();
if (adj[u].empty()) continue;
int v = *adj[u].begin();
adj[u].clear();
adj[v].erase(u);
}
}
if (remaining_nodes <= 1) {
return 0;
}
sequence of size n whose sum of elements equals sequence_sum, and the absolute
values of the elements form a permutation of size n. The utility reports the lexicographically
Given two integers, n, and sequence_sum, return the lexicographically smallest sequence
●
2. The absolute values of its elements form a permutation of size n.
Given two permutations x and y, x is lexicographically smaller than y if there exists an index
i where x[i] < y[i] and for this smallest index j < i, x[j] == y[j]. This means
that when comparing two elements by scanning from the start, the first position at which they
differ determines their order. If the element in x is less than the corresponding element in y
Examples
Example 1:
Suppose n = 5, sequence_sum = 9
Sequence Sum
[-1, 2, 3, 4, 5] 9
[-2, 1, 3, 4, 5] 9
[-3, 1, 2, 4, 5] 9
[3, 4, 5, -2, -1] 9
[3, 2, 1, 4, 5] 9
Explanation: Now we can clearly see [-3, 1, 2, 4, 5] is lexicographically smaller than
[-3, 2, 1, 4, 5] because 1 < 2 at the first index where they differ. The
Function Description
Complete the function getSmallestSequence in the editor below.
●
Returns
Constraints
● 1 <= n <= 10^5
● -10^10 <= sequence_sum <= 10^10
Sol:
#include <vector>
#include <numeric>
std::vector<int> result;
result.reserve(n);
std::vector<bool> used(n + 1, false);
long long current_target_sum = sequence_sum;
long long sum_of_unused_abs = max_total_sum;
int v = -k;
long long sum_of_abs_for_rem = sum_of_unused_abs - k;
long long min_rem_sum = -sum_of_abs_for_rem;
long long max_rem_sum = sum_of_abs_for_rem;
long long rem_target_sum = current_target_sum - v;
●
result.push_back(v);
current_target_sum -= v;
used[k] = true;
sum_of_unused_abs -= k;
found_choice_for_i = true;
break;
}
}
}
if (found_choice_for_i) {
continue;
}
int v = k;
long long sum_of_abs_for_rem = sum_of_unused_abs - k;
long long min_rem_sum = -sum_of_abs_for_rem;
long long max_rem_sum = sum_of_abs_for_rem;
long long rem_target_sum = current_target_sum - v;
return result;
}
●
You are a developer at Amazon evaluating the performance of processing units. There are n
processes, where each process i runs from starts[i] to ends[i] (both inclusive).
Examples
Example 1:
Input:
starts = [0, 1, 2]
ends = [2, 10, 9]
query_process = [0, 2]
query_start = [1, 4]
query_end = [10, 9]
The following table illustrates the process status over time based on the example input (note:
the `starts` and `ends` arrays might lead to a slightly different interpretation of process
activity than the table's "Process Status" events):
●
3 - [1, 2]
4 - [1, 2]
5 - [1, 2]
7 - [2]
8 - [2]
9 process 2 ends []
10 - []
11 - []
Explanation: (Note: The following explanation uses `query_process` values of 1 and 2 for the
first and second queries respectively, which might differ from the `query_process = [0, 2]` in
the input. This explanation is provided as-is from the problem statement.)
For the first query, the answer is the number of seconds between the 1st and 10th second
(both inclusive), where exactly 1 process is executing, i.e., (6, 7, 8, 9, 10). The answer to this
query is 5.
For the second query, the answer is the number of seconds between the 4th and 9th second
(both inclusive), where exactly 2 processes are executing, i.e., (4, 5). The answer to this
query is 2.
●
Output: [5,2]
Function Description
Complete the function getqueryAnswers in the editor below. The function must return an
array where ith integer denotes the answer to the ith query.
Returns:
Constraints
● 1 <= n <= 105
● 0 <= starts[i] <= ends[i] <= 109
● 0 <= q <= 105
● 0 <= query_start[j] <= query_end[j] <= 109
● 0 <= query_process[j] <= n
The first line contains an integer n, the size of starts and ends. The next n lines contain
elements of starts. The next n lines contain elements of ends. The next line contains an
integer q, the size of query_process, query_start, and query_end. The next q lines
Sample Input
●
3
0
1
2
3
2
10
9
2
0
2
1
4
10
9
Sample Output
5
2
Explanation:
(Note: This explanation section appears to have inconsistencies with the provided example
input and previous explanation.)
● Find the number of seconds between the 1st and 10th second (both inclusive) where
no process was being executed, i.e., (13, 14, 15, 16, 17, 18, 19, 20).
● Find the number of seconds between the 4th and 9th second (both inclusive) where
exactly 2 processes are executing, i.e., (4, 5).
Sol:
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <limits>
#include <iterator>
●
}
auto it_k = intervals_by_count.find(k);
if (it_k == intervals_by_count.end()) {
return 0;
}
if (intervals.empty()) {
return 0;
}
if (idx == 0) {
return 0;
}
return total_len;
}
●
for (size_t i = 0; i < starts.size(); ++i) {
events[starts[i]]++;
if (ends[i] < std::numeric_limits<int>::max()) {
events[ends[i] + 1]--;
}
}
intervals_by_count[current_count].push_back({last_time, time -
1});
}
current_count += change;
last_time = time;
}
●
std::vector<int> answers;
answers.reserve(query_process.size());
for (size_t i = 0; i < query_process.size(); ++i) {
int p = query_process[i];
int s = query_start[i];
int e = query_end[i];
answers.push_back(static_cast<int>(len_at_end -
len_before_start));
}
return answers;
}
Code Question 2
Problem Description
At Amazon's internal developer summit, two engineers, Alex and Charlie are competing in a
fun coding duel challenge. They are given a string S composed of lowercase English letters.
● Alex and Charlie take turns removing one character at a time, with Alex going first.
● The game continues until only one character is left in the string.
● Alex's strategy: Remove a character that results in the smallest possible string
(lexicographically).
● Charlie's strategy: Remove a character that results in the largest possible string
(lexicographically).
●
Your task is to simulate this process and determine the final character left in the string after
all removals with Alex making the first move.
Examples
Example 1:
Consider the string S = 'cat'
1. Turn 1: Alex (minimize) tries removing each character and evaluates the resulting strings:
The final character left in the string is 't'. Hence, the answer is 't'.
Sample Case 0:
Input: S = "abcde"
Output: c
Explanation:
Here, S="abcde"
●
● Charlie would remove character 'a' (at index 0) making S="bcd"
● Alex would remove character 'd' (at index 2) making S="bc"
● Charlie would remove character 'b' (at index 0) making S="c"
Sample Case 1:
Input: S = "hacker"
Output: e
Explanation:
Here, S="hacker"
Function Description
Complete the function finalCharacter in the editor below.
char finalCharacter(string s) {
// Complete the 'finalCharacter' function below.
// The function is expected to return a CHARACTER.
// The function accepts STRING s as parameter.
}
Constraints
● 1 <= |S| <= 10^6
● String S consists only of English lowercase letters (a-z).
●
Sol:
#include <bits/stdc++.h>
char finalCharacter(string s) {
int n = dq.size();
if (alexTurn) {
dq.pop_front();
else
●
dq.pop_back();
} else {
dq.pop_front();
else
dq.pop_back();
alexTurn = !alexTurn;
return dq.front();
Problem Description
AWS provides scalable systems. A set of n servers are used for horizontally scaling an application. The goal is to have the
computational power of the servers in non-decreasing order. To do so, you can increase the computational power of each
server in any contiguous segment by x. Choose the values of x such that after the computational powers are in non-decreasing
●
The function findMinimumSum has the following parameter(s):
Returns:
● long: the minimum possible sum of integers required to make the array non-decreasing
Examples
Example 1:
There are n = 5 servers and their computational power = [3, 4, 1, 6, 2].
Explanation: Add 3 units to the subarray (2,4) and 4 units to the subarray (4,4). The final arrangement of the servers is [3, 4,
Example 2:
Input:
n = 3
power = [3, 2, 1]
Output: 2
Explanation: Add 1 unit to subarray (1,2) and 1 unit to subarray (2,2). The final arrangement of servers is [3, 3, 3].
Example 3:
Input:
n = 4
power = [3, 5, 2, 3]
Output: 3
Explanation: Add 3 units to subarray (2,3). The final arrangement of servers is [3, 5, 5, 6].
●
Constraints
● 1 <= n <= 10^5
● 1 <= power[i] <= 10^9
Sol:
#include <algorithm>
if (power_count <= 1) {
return 0;
●
if (b_increase > 0) {
total_min_sum += b_increase;
prev_b = current_b;
return (long)total_min_sum;
Problem Description
In a newly planned city, where a city is located at each integral coordinate in a 2-dimensional
plane, there are n Amazon retailers. The i-th retailer residing in the city at the coordinate
(x_i, y_i) can deliver to all the cities covered by the rectangle having the 4 corner points
(0, 0), (x_i, 0), (x_i, y_i), (0, y_i). We say that a point (a, b) is covered by
a rectangle if it lies inside the rectangle or on its boundaries. Note that no 2 retailers reside in
the same city.
Given q requests of the form (a, b), determine the number of retailers who can deliver to
Complete the function findNumRetailers in the editor below. The function is expected to
return an INTEGER_ARRAY.
●
vector findNumRetailers(vector> retailers, vector> requests)
The function has the following parameters:
Returns:
int array[q]: the i-th element is the answer to the i-th query.
Examples
Example 1:
Input: retailers = [[1, 2], [2, 3], [1, 5]], requests = [[1, 1],
[1, 4]]
Output: [3, 1]
Explanation: In this example, we have 3 retailers in the cities (1, 2), (2, 3), and (1, 5).
● For the first request, all 3 retailers can deliver to the city at the coordinate (1, 1).
● For the second request, only the third retailer can deliver to the city at the coordinate
(1, 4).
Example 2:
Input: retailers = [[1, 4], [2, 4], [1, 5]], requests = [[2, 6],
[1, 4]]
Output: [0, 3]
Explanation:
● For the first request, none of the retailers can deliver to the city at the coordinates (2,
6).
● For the second request, all 3 retailers can deliver to the city at the coordinates (1, 4).
Constraints
● 1 <= n, q <= 7.5 * 10^4
● 1 <= retailers[i][0] <= 10^9
●
● 1 <= retailers[i][1] <= 10^9
● 0 <= requests[i][0] <= 10^9
● 0 <= requests[i][1] <= 10^9
● No two retailers share the same coordinates.
Sol:
#include <vector>
#include <algorithm>
struct Request {
int x, y, id;
};
class FenwickTree {
private:
std::vector<int> bit;
int size;
public:
FenwickTree(int sz) : size(sz), bit(sz + 1, 0) {}
std::vector<int> findNumRetailers(const
std::vector<std::vector<int>>& retailers, const
std::vector<std::vector<int>>& requests) {
int n = retailers.size();
int q = requests.size();
if (q == 0) {
return {};
}
●
std::vector<int> y_coords;
y_coords.reserve(n + q);
for (const auto& r : retailers) {
y_coords.push_back(r[1]);
}
for (const auto& req : requests) {
y_coords.push_back(req[1]);
}
std::sort(y_coords.begin(), y_coords.end());
y_coords.erase(std::unique(y_coords.begin(), y_coords.end()),
y_coords.end());
FenwickTree ft(y_coords.size());
std::vector<Request> reqs(q);
for (int i = 0; i < q; ++i) {
reqs[i] = {requests[i][0], requests[i][1], i};
}
std::sort(reqs.begin(), reqs.end(), [](const Request& a, const
Request& b) {
return a.x > b.x;
});
std::vector<int> ans(q);
int retailer_idx = 0;
●
int total_added = retailer_idx;
int count_less_than_b = ft.query(comp_by - 1);
ans[req.id] = total_added - count_less_than_b;
}
return ans;}
● In each operation, two characters from the dataset are selected and removed.
● Each operation has an associated cost:
● matchCost: the cost of removing two identical characters.
● mismatchCost: 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.
Returns:
●
● int: the minimum cost to clean up the dataset or make the string empty
Examples
Example 1:
Input: dataset = "ouio", matchCost = 2, mismatchCost = 4
Output: 6
Explanation:
Operation 1:
● Action: Remove the first and last characters of the dataset, resulting in the string
dataset = 'ui'.
● Cost: mismatchCost = 2 (since both removed characters, 'o' and 'o', are the same).
Operation 2:
● Action: Delete the remaining characters of 'ui', making dataset an empty string.
● Cost: mismatchCost = 4 (since the removed characters, 'u' and 'i', are different).
Example 2:
Input: dataset = "aaabca", matchCost = 3, mismatchCost = 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 matchCost = 3
because both removed characters are equal to 'a'. In the next operation, the first and third
characters are deleted, making dataset = "ba". The cost of this operation is
mismatchCost = 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 mismatchCost = 2 because the removed characters are not equal.
●
Example 3:
Input: dataset = "xxch", matchCost = 5, mismatchCost = 5
Output: 10
Explanation: In the first operation, the first two characters are deleted, resulting in dataset
= "ch". The cost of this operation is matchCost = 5, because both removed characters
are equal to 'x'. In the next operation, the remaining two characters are deleted, making
dataset an empty string. The cost of this operation is mismatchCost = 5, because the
removed characters are not equal. Hence, the total cost is 5 + 5 = 10.
Constraints
● 2 <= |dataset| <= 105
● |dataset| is even
● 1 <= matchCost, mismatchCost <= 104
Sol:
#include <bits/stdc++.h>
using namespace std;
●
// costs equal -> any feasible number of match pairs yields same cost
chosenMatchPairs = max_matchPairs;
}
centers. The center of the ith package is represented by an array centers[i]. The
specialist is allowed to perform one operation at a time. Each operation is described below:
1. If the queue has two or more packages, the specialist can choose two packages x
and y from the queue if they are from different distribution centers (i.e., centers[x]
!= centers[y]) and process both of them.
2. If the queue has one or more packages, the specialist can choose one package x
from the queue and process it.
Note: After processing a package it gets removed from the queue, and the rest of the
packages which are currently not processed come together keeping the order the same as
before.
Given n packages and an array centers, find the minimum number of operations that the
Function Description
Complete the function findMinimumOperations in the editor below.
●
● int centers[n]: the distribution center of each package.
Returns
● int: the minimum number of operations that the specialist has to perform to process
all of the packages.
#include <bits/stdc++.h>
/*
* Complete the 'findMinimumOperations' function below.
*
* The function is expected to return an INTEGER.
* The function accepts INTEGER_ARRAY centers as parameter.
*/
int main() {
Examples
Example 1:
Input: n = 4, centers = [1,3,1,2]
Output: 2
Explanation: Given n=4 and centers=[1, 3, 1, 2].
1. Choose packages from centers 1 and 3 (different centers). Remaining packages:
[1, 2]. (1 operation)
2. Choose packages from centers 1 and 2 (different centers). Remaining packages: [].
(1 operation)
Example 2:
Input: n = 4, centers = [9,5,9,9]
●
Output: 3
Explanation: Given n=4 and centers=[9, 5, 9, 9].
1. Choose packages from centers 9 and 5 (different centers). Remaining packages:
[9, 9]. (1 operation)
2. Now, the remaining packages are from centers [9, 9]. Since both are from the
same center, we cannot choose two packages in one operation. We must process
them one by one. Choose one package from center 9. Remaining packages: [9]. (1
operation)
3. Choose the last package from center 9. Remaining packages: []. (1 operation)
Constraints
● 1 <= n <= 105
● 1 <= centers[i] <= 109
Sol:
#include <bits/stdc++.h>
int n = centers.size();
unordered_map<int, int> freq_map;
int max_freq = 0;
●
if (max_freq > n - max_freq) {
return max_freq;
} else {
return (n + 1) / 2;
}
}
int main() {
return 0;
}
There are `streamCount` data channels that needs to be connected to two processing
nodes, one as the main connection and the other as the secondary. Each data channel must
utilize a unique pair of nodes for its connections.
The `dataFlow` for each data channel is defined as the sum of the bandwidth of its main and
secondary nodes.
Given an integer array `bandwidth` and an integer `streamCount`, find the maximum total
`dataFlow` that can be achieved by optimally selecting unique pair of connections for each
data channel.
Note: A pair of nodes (x,y) is said to be unique if no other channel 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 node for main and secondary connections, which means that
(x,x) is a valid pair for the connection.
●
long determineMaxDataFlow(vector<int> bandwidth, long streamCount)
The function has the following parameters:
Returns: `long`: the maximum total dataFlow from the unique connections of node pairs.
Examples
Example 1:
Input: bandwidth = [6, 4, 7], streamCount = 4
Output: 52
Explanation: The data channels can select their connections among the following 9 possible
node pairs: [1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]. (Assuming 1-based
indexing of bandwidth array). However each data channel must select a unique pair of
nodes. To achieve the maximum total dataFlow, the data channels can optimally choose the
pairs [3, 3], [3, 1], [1, 3], [1, 1] to obtain the maximum sum of dataFlow = (7 + 7) + (7 + 6) +
(6 + 7) + (6 + 6) = 52.
Example 2:
Input:
n = 5
bandwidth = [5, 4, 8, 4, 7]
streamCount = 6
Output: 86
Explanation: The six pairs of processing nodes with the highest sum of dataFlow are: [3, 3],
[3, 5], [5, 3], [5, 5], [3, 1], [1, 3]. (Assuming 1-based indexing) Thus total dataFlow will be
calculated as: 16 (for [3, 3]) + 15 (for [3, 5]) + 15 (for [5, 3]) + 14 (for [5, 5]) + 13 (for [3, 1]) +
13 (for [1, 3]) = 86. Therefore, the total dataFlow = 86. Hence return 86 as answer.
Example 3:
Input:
n = 4
bandwidth = [14, 120, 8, 14]
streamCount = 4
Output: 626
Explanation: The four pairs of processing nodes with the highest sum of dataFlow are: [2, 2],
[2, 1], [2, 4], [1, 2] (Assuming 1-based indexing). The total dataFlow is calculated as: 240 (for
●
[2, 2]) + 134 (for [2, 1]) + 134 (for [2, 4]) + 118 (for [1, 2]) = 626. Thus, the total dataFlow =
626. Hence return 626 as answer.
Constraints
● `1 <= n <= 2 * 10^5`
● `1 <= bandwidth[i] <= 2 * 10^3`
● `1 <= streamCount <= min(10^3, n^2)`
Sol:
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
●
return ans;
}
int main() {
vector<int> bandwidth = {14, 120, 8, 14};
long streamCount = 4;
cout << determineMaxDataFlow(bandwidth, streamCount) << "\n"; // Output: 626
}
volume. The challenge is to evaluate the "packing efficiency" of the collection, aiming for
proper utilization of space.
More specifically, there is an array volumes, where volumes[i] represents the volume of
● l <= i <= r (meaning i is an index within the subarray B, from its start l to its
end r)
● For every index j such that i < j <= r, volumes[i] > volumes[j]
The total packing efficiency of the entire collection is calculated by summing the packing
efficiency across all subarrays of a given size k.
Given an array volumes of size n and an integer k, compute the total packing efficiency of
the collection.
Examples
●
Example 1:
Input:
n = 6
volumes = [3, 6, 2, 9, 4, 1]
k = 3
Output: 8
Explanation:
3:
●
● For i = 3 (value volumes[3]=9): 9 > volumes[4]=4 is true, and 9 >
volumes[5]=1 is true. Satisfies.
● For i = 4 (value volumes[4]=4): 4 > volumes[5]=1 is true. Satisfies.
● For i = 5 (value volumes[5]=1): No j such that 5 < j <= 5. Satisfies.
Sol:
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> volumes = {3, 6, 2, 9, 4, 1};
int k = 3;
cout << totalPackingEfficiency(volumes, k) << endl; // Output: 8
}
●
Minimum Operations to Dispatch Items
Problem Description
The logistics coordinator at an Amazon fulfillment center needs to dispatch `n` items from
different warehouses, the warehouse of the `i`th item is represented by an array
`warehouses[i]`. The coordinator is allowed to perform one operation at a time. Each
operation is described below:
1. If the inventory has two or more items, the coordinator can select two items `x` and
`y` from the inventory if they are stored in different warehouses. i.e. `warehouses[x]
!= warehouses[y]` and dispatch both of them.
2. If the inventory has one or more items, the coordinator can select one item `x` from
the inventory and dispatch it.
Note: After dispatching an item it gets removed from the inventory, and the rest of the items
which are currently not dispatched come together keeping the order the same as before.
Given `n` items and an array `warehouses`, find the minimum number of operations that the
coordinator has to perform to dispatch all of the items.
Examples
Example 1:
●
Input: warehouses = [2, 9, 7, 8, 8]
Output: 3
Explanation: The problem statement illustrates the operations to dispatch all items in 3
steps.
Example 2:
Input: warehouses = [1, 3, 1, 2]
Output: 2
Explanation: The problem statement illustrates the operations to dispatch all items in 2
steps.
Example 3:
Input: warehouses = [9, 5, 9, 9]
Output: 3
Explanation: The problem statement illustrates the operations to dispatch all items in 3
steps.
Constraints
● `1 <= n <= 10^5`
● `1 <= warehouses[i] <= 10^9`
Sol:
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> w1 = {2, 9, 7, 8, 8};
vector<int> w2 = {1, 3, 1, 2};
●
vector<int> w3 = {9, 5, 9, 9};
Code Question 1
Problem Description
Your team at Amazon 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
answers students can provide. You have been asked to examine the impact of this limit on
the ability of students to pass certain subjects within quiz modules. To do this, please review
and solve for the following: imagine a student has already answered answered[i]
questions in each of the n subjects, and still has time to answer a total of q more questions
overall. For each ith subject, the number of questions answered has to be at least
needed[i] in order to pass. Determine the maximum number of subjects the student can
pass if the q additional answered questions are optimally distributed among the subjects.
For example, consider that there are n = 2 subjects and needed = [4, 5] answered
questions, respectively, to pass. Imagine the student has answered answered = [2, 4]
questions in the two subjects so far, and can answer another q = 1 question 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.
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.
●
● q: an integer
Examples
Example 1:
Input:
n = 3
answered = [24, 27, 0]
needed = [51, 52, 100]
q = 100
Output: 2
Explanation: The questions still needed for each subject are [max(0, 51-24), max(0,
52-27), max(0, 100-0)] = [27, 25, 100]. To pass the first two subjects, 27 +
pass these two subjects. To pass the third subject alone would require 100 questions.
Example 2:
Input:
n = 3
answered = [24, 27, 0]
needed = [51, 52, 97]
q = 200
Output: 3
Explanation: The questions still needed for each subject are [max(0, 51-24), max(0,
52-27), max(0, 97-0)] = [27, 25, 97]. To pass all three subjects, a total of 27 +
25 + 97 = 149 additional questions are required. Since q = 200 and 149 <= 200,
there are enough questions to pass all three subjects. The remaining 200 - 149 = 51
Constraints
● 1 <= n <= 105
● 0 <= answered[i] <= 109
● 0 <= needed[i] <= 109
●
● 0 <= q <= 109
● 0 <= answered[i] <= needed[i]
Sol:
#include <bits/stdc++.h>
using namespace std;
sort(remaining.begin(), remaining.end());
int passed = 0;
for (int i = 0; i < n; i++) {
if (q >= remaining[i]) {
q -= remaining[i];
passed++;
} else break;
}
return passed;
}
int main() {
vector<int> answered1 = {24, 27, 0};
vector<int> needed1 = {51, 52, 100};
int q1 = 100;
cout << findMaximumNum(answered1, needed1, q1) << "\n"; // Output: 2
●
A financial analyst for Amazon Web Services (AWS) is responsible for a portfolio of
profitable stocks represented by an array. Each item in the array represents the yearly profit
of a corresponding stock. The Amazonian gathers all distinct pairs of stocks that yielded the
target profit. Distinct pairs are pairs that differ in at least one element. Given the array of
profits, find the number of distinct pairs of stocks where the sum of each pair's profits is
exactly equal to the target profit.
Returns:
Examples
Example 1:
Input: stocksProfit = [5, 7, 9, 12, 11, 6, 6, 3], target = 12
Output: 3
Explanation: There are 4 pairs of stocks that have the sum of their profits equal to the target
12. Note that because there are two instances of 6 in stocksProfit there are two pairs
matching (6, 6). stocksProfit indices 2 and 7, and indices 3 and 8, but only one can be
included. There are 3 distinct pairs of stocks: (6, 6), (3, 9), and the return value is 3.
Example 2:
Input: stocksProfit = [1, 3, 46, 1, 3, 9], target = 47
Output: 1
Explanation: There are 4 pairs where stocksProfit[i] + stocksProfit[j] = 47:
●
1. (stocksProfit[0] = 1, stocksProfit[2] = 46)
2. (stocksProfit[2] = 46, stocksProfit[0] = 1)
3. (stocksProfit[3] = 1, stocksProfit[2] = 46)
4. (stocksProfit[2] = 46, stocksProfit[3] = 1)
Since all four pairs contain the same values, there is only 1 distinct pair of stocks: (1, 46).
Example 3:
Input: stocksProfit = [6, 3, 9, 3, 6], target = 12
Output: 2
Explanation: There are 5 pairs where stocksProfit[i] + stocksProfit[j] = 12:
The first 2 pairs are the same, as are the last 4. There are only 2 distinct pairs of stocks: (3,
9) and (6, 6).
Constraints
● 1 <= n <= 5 * 10^5
● 0 <= stocksProfit[i] <= 10^9
● 0 <= target <= 5 * 10^9
Sol:
#include <bits/stdc++.h>
using namespace std;
int count = 0;
●
for (auto& [x, f] : freq) {
long long y = target - x;
if (freq.find(y) != freq.end()) {
if (x == y) {
if (f >= 2) count++; // pair (x, x)
} else if (x < y) {
count++; // pair (x, y)
}
}
}
return count;
}
int main() {
vector<int> profits1 = {5, 7, 9, 12, 11, 6, 6, 3};
cout << getDistinctPairs(profits1, 12) << "\n"; // Output: 3
Medians
Problem Description
A new Amazon intern encountered a challenging task.
Currently, the intern has n integers, where the value of the ith element is represented by the
The intern is curious to play with arrays and subsequences and thus asks you to join him.
Given n integer, array values, and an integer k, the intern needs to find the maximum and
Function Description
Complete the function medians in the editor below.
●
● int values[n]: the value of integers.
● int k: the given integer.
Returns
int[]: the maximum and minimum overall subsequences of length k in the form
Examples
Example 1:
Input: n = 3, values = [1, 2, 3], k = 2
Output: [2, 1]
Explanation:
[1, 2] 1
[1, 3] 1
[2, 3] 2
Here, the maximum median present is 2 and the minimum median in the subsequence
present is 1.
Example 2:
Input: n = 2, values = [56, 21], k = 1
Output: [56, 21]
Explanation:
●
Subsequences of length k median
[56] 56
[21] 21
The maximum median present is 56 and the minimum median in the subsequence present is
21.
Example 3:
Input: n = 5, values = [16, 21, 9, 2, 78], k = 5
Output: [16, 16]
Explanation:
There is only one subsequence of length 5, hence the maximum median and minimum
median are 16.
Constraints
● 1 ≤ n ≤ 106
● 0 ≤ values[i] ≤ 109
● 1 ≤ k ≤ n
Sol:
#include <bits/stdc++.h>
using namespace std;
int medianIndex = (k - 1) / 2;
●
int minMedian = values[medianIndex];
int maxMedian = values[n - k + medianIndex];
int main() {
vector<int> v1 = {1, 2, 3};
auto res1 = medians(v1, 2);
cout << res1[0] << " " << res1[1] << "\n"; // 2 1
Code Question 2
Problem Description
Software developed these days is subject to frequent cyber attacks.
To prevent the attacks from succeeding, the security team at Amazon ensures the security of
its systems by running tests against n files, where the ith file has size fileSize[i] and
The ith virus attacks the ith file and is only effective against a file with size affinity[i].
In one operation, the team can choose 2 files, i and j, and swap their sizes, i.e.,
●
Given the sizes of files and the virus' affinities, find the minimum number of operations
performed such that fileSize[i] != affinity[i] for each file from 0 to n-1. If it is
Returns:
Examples
Example 1:
Input: n = 5, fileSize = [2, 2, 1, 1, 2], affinity = [2, 1, 1, 1,
2]
Output: 2
Explanation: Initially, we have fileSize = [2, 2, 1, 1, 2] and affinity = [2,
1, 1, 1, 2].
●
● Operation 2: Swap fileSize[3] with fileSize[4].
fileSize becomes [1, 2, 2, 2, 1].
In this modified file size array, none of the file sizes match the corresponding affinity.
Example 2:
Input: n = 5, fileSize = [1, 2, 3, 2, 3], affinity = [1, 2, 3, 2,
3]
Output: 3
Explanation: Given, n = 5, fileSize = [1, 2, 3, 2, 3], affinity = [1, 2,
4.
Example 3:
Input: n = 5, fileSize = [2, 2, 2, 1, 1], affinity = [1, 1, 1, 1,
2]
Output: -1
Explanation: Given, n = 5, fileSize = [2, 2, 2, 1, 1], affinity = [1, 1,
Constraints
● 1 <= n <= 105
● 1 <= fileSize[i], affinity[i] <= 109
Sol:
●
#include <bits/stdc++.h>
using namespace std;
int maxFreq = 0;
for(auto& [val, f] : freq)
maxFreq = max(maxFreq, f);
int main() {
vector<int> file1 = {2,2,1,1,2};
vector<int> aff1 = {2,1,1,1,2};
cout << calculateMinimumSwaps(file1, aff1) << "\n"; // 2
●