Skip to main content

Placements '24: Assessments [Part 3]

Image of the author

Eshaan Aggarwal @EshaanAgg

This is the third part of the series on online assessments that I witnessed during the season of 2024. The previous parts can be found here and here.


Phone Pe

Other Campus Questions

  1. You are given a tree with nn nodes. Each node has arr[i]arr[i] amount of apples on it. You start walking from the node 11, and on the walk you randomly choose any unvisited node connected to the current node with equal probability. You can only visit each node once. You can eat the apples on the node you are currently on. What is the expected number of apples you will eat?

    Solution

    We will perform a single DFS to calculate the same. The time complexity of the same would be O(n)O(n).

    double dfs(int u, int p, vector<vector<int>> &g, vector<int> &arr) {
    int cntChild = 0;
    for (int v : g[u]) {
    if (v == p) continue;
    cntChild++;
    }
    if (cntChild == 0)
    return arr[u];
    double ans = arr[u], p = 1.0 / (double)cntChild;
    for (int v : g[u]) {
    if (v == p) continue;
    ans += p * dfs(v, u, g, arr);
    }
    return ans;
    }
    int main() {
    int n;
    cin >> n;
    vector<int> arr(n);
    for (int i = 0; i < n; i++) {
    cin >> arr[i];
    }
    vector<vector<int>> g(n);
    for (int i = 0; i < n - 1; i++) {
    int u, v;
    cin >> u >> v;
    u--, v--;
    g[u].push_back(v);
    g[v].push_back(u);
    }
    cout << fixed << setprecision(10) << dfs(0, -1, g, arr) << endl;
    }
  2. There are nn numbers of a board. In one operation, you will pick two numbers xx and yy from the board, erase them and add the following number back to the board:

    • xyx - y if both xx and yy have the same parity.
    • x+yx + y if both xx and yy have different parity.

    Calculate how many different final numbers can be present on the board.

    Constraints:

    • 1n501 \leq n \leq 50
    • 1ai1001 \leq a_i \leq 100
  3. There is a contest where two flags have been placed among checkpoints on the map of Haven. Checkpoints are connected by mm roads, it is possible that there are checkpoints between which no path exists, meaning there are no roads connecting them. You are given a checkpoint aa where you will start your journey, and you have to collect both flags, placed at checkpoints bb and cc in order (bb first and then cc). You can pass through checkpoints more than once. However, you have to pay a price to use the road, so if someone goes along a road then every time he should pay the price for that road. You are given an array of costs of size mm. You have to distribute prices such that each price of the road corresponds to only one road, so that the cost of collecting both flags will be minimal and hence win the contest. You cannot rearrange prices after the start of the contest. It is guaranteed that there are no self loops or multiple edges in the graph.

    Constraints:

    • 1n,m1051 \leq n, m \leq 10^5
    • 1a,b,cn1 \leq a, b, c \leq n
    • 1costi1091 \leq cost_i \leq 10^9
Solution
  1. Raju works for PhonePe and needs to deliver QR codes to Vanous merchants in a city laid out as an inom grid, Each shop in the grid requires a certain number of QR codes. Raju starts his journey at the top-left corner of the grid (0,0)(0,0) and needs to reach the bottom-right corner (n1,m1)(n-1, m-1). He can only move right or down at any step. Raju wants to distribute the maximum number of QR codes in a single commute. But there’s a twist, To assist a merchant more efficiently Raju chooses to double the number of QR codes for one specific merchant along his path. However, he can only do this for one shop in his entire Journey. Your task is to help Raju determine the maximum number of QR’s he would need on his way to the destination, Help considering the option to double the value of exactly one cell.

    Constraints:

    • 1n,m1031 \leq n, m \leq 10^3
    • 1aij1031 \leq a_{ij} \leq 10^3
    Solution
    int main()
    {
    int Y, X;
    cin >> Y >> X;
    vector<vector<int>> g(Y, vector<int>(X));
    for (int i = 0; i < Y; i++)
    for (int j = 0; j < X; j++)
    cin >> g[i][j];
    long long dp[Y][X][2];
    memset(dp, 0, sizeof(dp));
    dp[0][0][0] = g[0][0];
    dp[0][0][1] = g[0][0] * 2;
    for (int y = 0; y < Y; y++)
    for (int x = 0; x < X; x++)
    {
    if (x != 0)
    {
    dp[y][x][0] = max(dp[y][x][0], dp[y][x - 1][0] + g[y][x]);
    dp[y][x][1] = max({
    dp[y][x][1],
    dp[y][x - 1][1] + g[y][x],
    dp[y][x - 1][0] + g[y][x] * 2,
    });
    }
    if (y != 0)
    {
    dp[y][x][0] = max(dp[y][x][0], dp[y - 1][x][0] + g[y][x]);
    dp[y][x][1] = max({
    dp[y][x][1],
    dp[y - 1][x][1] + g[y][x],
    dp[y - 1][x][0] + g[y][x] * 2,
    });
    }
    }
    cout << dp[Y - 1][X - 1][1] << endl;
    }
  2. To ensure seamless transactions, PhonePe needs to optimize its server network to minimize communication costs across these locations You are given a network of NN machines, which can either be server machines or client machines, and MM directed, weighted edges representing the network cost to travel from one machine to its neighbor machine. If a path exists from one machine to another, then network cost is defined as the sum of edge weights via that path. Your task is to determine the minimum sum of network cost to reach all machines (client and server machines) from any server. Additionally, each client machine can be upgraded to a server machine at a given one-time cost. This means the number of server machines will increase by 11, but with additional cost.

    • The cost to reach itself for a client machine with server capabilities is zero since reaching itself needs no edge traversal.
    • The cost to reach a server machine from itself is zero.

    Input Format:

    • An integer NN representing the total number of machines. Machines are labeled from 11 to NN
    • An integer CC representing the total number of client.
    • machinesmachines: A list of integers containing client machine nodes.
    • An integer SS representing the total number of server machines.
    • A list of integers containing server machine nodes.
    • An integer MM representing the number of directed, weighted edges.
    • A list of MM tuples (u,v,w)(u,v,w), where uu is the starting machine, vv is the destination machine, and ww is the network cost to travel from uu to vv.
    • An integer KK representing the number of upgradable client machines
    • A K×2K \times 2 size two dimensional integer list AA, where A[i][0]A[i][0] denotes client machine node and A[i][1]A[i][1] denotes upgradation cost to have server capabilities.

    Return the minimum network cost sum. Return 1-1 if it is not possible to reach all machines. Since the answer can overflow, you need to return the answer modulo (106+7)(10^6+7).

    Constraints:

    • 1N1001 \leq N \leq 100
    • 0MN20 \leq M \leq N^2
    • 1u,vN1 \leq u, v \leq N
    • 0w1060 \leq w \leq 10^6
    • 0k100 \leq k \leq 10
    • 1A[i][0]1001 \leq A[i][0] \leq 100
    • 0A[i][1]1060 \leq A[i][1] \leq 10^6
    Solution

    We will use a bitmask on the upgradable servers and a multi-source Dijkstra to solve this problem. The time complexity of the solution would be O(2k(N+M)logN)O(2^k \cdot (N + M) \log N).

    1
    int main()
    2
    {
    3
    int n;
    4
    cin >> n;
    5
    6
    // Client -> 1, Server -> 2
    7
    vector<int> arr(n + 1, 0);
    8
    9
    int c;
    10
    cin >> c;
    11
    for (int i = 0; i < c; i++)
    12
    {
    13
    int x;
    14
    cin >> x;
    15
    arr[x] = 1;
    16
    }
    17
    18
    int s;
    19
    cin >> s;
    20
    for (int i = 0; i < s; i++)
    21
    {
    22
    int x;
    23
    cin >> x;
    24
    arr[x] = 2;
    25
    }
    26
    27
    vector<vector<pair<int, int>>> g(n + 1);
    28
    int m;
    29
    cin >> m;
    30
    for (int i = 0; i < m; i++)
    31
    {
    32
    int u, v, w;
    33
    cin >> u >> v >> w;
    34
    g[u].push_back({v, w});
    35
    }
    36
    37
    int k;
    38
    cin >> k;
    39
    vector<vector<int>> A(k, vector<int>(2));
    40
    for (int i = 0; i < k; i++)
    41
    cin >> A[i][0] >> A[i][1];
    42
    43
    long long ans = 1e18;
    44
    45
    for (int mask = 0; mask < (1 << k); mask++)
    46
    {
    47
    long long curCost = 0;
    48
    49
    vector<long long> dist(n + 1, 1e18);
    50
    priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;
    51
    52
    // Add all the original servers
    53
    for (int i = 1; i <= n; i++)
    54
    if (arr[i] == 2)
    55
    {
    56
    dist[i] = 0;
    57
    pq.push({0, i});
    58
    }
    59
    60
    // Add all the new servers
    61
    for (int i = 0; i < k; i++)
    62
    if (mask & (1 << i))
    63
    {
    64
    dist[A[i][0]] = 0;
    65
    pq.push({0, A[i][0]});
    66
    curCost += A[i][1];
    67
    }
    68
    69
    while (!pq.empty())
    70
    {
    71
    auto [d, u] = pq.top();
    72
    pq.pop();
    73
    74
    if (dist[u] < d)
    75
    continue;
    76
    77
    for (auto [v, w] : g[u])
    78
    if (dist[v] > dist[u] + w)
    79
    {
    80
    dist[v] = dist[u] + w;
    81
    pq.push({dist[v], v});
    82
    }
    83
    }
    84
    85
    bool valid = true;
    86
    for (int i = 1; i <= n; i++)
    87
    if (arr[i] == 1)
    88
    {
    89
    if (dist[i] == 1e18)
    90
    {
    91
    valid = false;
    92
    break;
    93
    }
    94
    curCost += dist[i];
    95
    }
    96
    97
    if (valid)
    98
    ans = min(ans, curCost);
    99
    }
    100
    101
    if (ans == 1e18)
    102
    ans = -1;
    103
    else
    104
    ans %= ((long long)1e6 + 7);
    105
    106
    cout << ans << endl;
    107
    }
  3. There are houses numbered from 11 to nn. Alice is intially at house xx, and Bob is at house yy. In one second, they can either move one house to the left or one house to the right. What is the minimum time they need to visit all the houses atleast once? There are tt testcases in one test file.

    Constraints:

    • 1t1051 \leq t \leq 10^5
    • 1n1091 \leq n \leq 10^9
    • 1x,yn1 \leq x, y \leq n
    Solution
    1
    bool check(int time, int n, int x, int y) {
    2
    int cnt1 = x + max(0, time - 2 * (x - 1));
    3
    cnt1 = max(cnt1, (time + x + 1)/2);
    4
    5
    int cnt2 = max(n - y + 1 + max(0, time - 2 * (n - y)));
    6
    cnt2 = max(cnt2, n - (n + y - time + 1)/2 + 1);
    7
    8
    return cnt1 + cnt2 >= n;
    9
    }
    10
    11
    void solve() {
    12
    int n, x, y;
    13
    cin >> n >> x >> y;
    14
    15
    if (x > y)
    16
    swap(x, y);
    17
    18
    int l = max(x - 1, n - y), r = 2 * n;
    19
    int ans;
    20
    while (l <= r) {
    21
    int m = l + (r - l) / 2;
    22
    if (check(m, x, y, n)) {
    23
    ans = m;
    24
    r = m - 1;
    25
    } else {
    26
    l = m + 1;
    27
    }
    28
    }
    29
    30
    cout << ans << endl;
    31
    }
    32
    33
    int main() {
    34
    int t;
    35
    cin >> t;
    36
    37
    while (t--)
    38
    solve();
    39
    }
  4. There is a country with nn cities and nn directed edges between them. It is desired to reorient the edges so that every city is reachable from every other city. Figure out the minimum cost to do the same. A city has atmost 22 edges in this nation. The cost of reversing a directed edge is equal to the weight of the edges. It is gauranteed that a solution always exists for the provided setting.

    Constraints:

    • 1n1051 \leq n \leq 10^5
    • 1ai1091 \leq a_i \leq 10^9
    Solution

    Under the given conditions, it can be seen that the final layout with be that of a loop. Thus we just need to figure out the minimum cost to make a loop. The time complexity of the solution would be O(n)O(n).

    1
    int main() {
    2
    int n;
    3
    cin >> n;
    4
    5
    vector<vector<int>> g(n);
    6
    map<pair<int, int>, int> cost;
    7
    for (int i = 0; i < n; i++) {
    8
    int u, v, w;
    9
    cin >> u >> v >> w;
    10
    u--, v--;
    11
    g[u].push_back(v);
    12
    g[v].push_back(u);
    13
    cost[{u, v}] = 0;
    14
    cost[{v, u}] = w;
    15
    }
    16
    17
    vector<int> vis(n, 0);
    18
    vector<int> cycle;
    19
    20
    function<void(int, int)> dfs = [&](int u, int p) {
    21
    vis[u] = 1;
    22
    cycle.push_back(u);
    23
    24
    for (int v : g[u]) {
    25
    if (v == p) continue;
    26
    if (!vis[v])
    27
    dfs(v, u);
    28
    }
    29
    };
    30
    dfs(0, -1);
    31
    32
    long long cost1 = 0, cost2 = 0;
    33
    for (int i = 0; i < n; i++) {
    34
    int u = cycle[i], v = cycle[(i + 1) % n];
    35
    cost1 += cost[{u, v}];
    36
    cost2 += cost[{v, u}];
    37
    }
    38
    cout << min(cost1, cost2) << endl;
    39
    }
  5. There are nn hurdles in a course and crossing each one increments your score by arr[i]arr[i]. An athelete can only cross at max kk consecutive hurdles on the course. What is the maximum score any athlete can get on the course?

    Constraints:

    • 1n1051 \leq n \leq 10^5
    • 1kn1 \leq k \leq n
    • 1arr[i]1091 \leq arr[i] \leq 10^9
    Solution

    We will use dynamic programming to solve this problem. Let us denote dp[i]dp[i] as the minimum sum of elements I must remove from the array arr[1i]arr[1 \ldots i] such that the condition mentioned in the question holds. We also define g[i]g[i] to be equal to dp[i1]+arr[i]dp[i-1] + arr[i], and the value of dp[i]dp[i] can be calculated as dp[i]=min(g[j])dp[i] = \min (g[j]) for the previous kk indices with respect to ii. We will use a deque to calculate the range minimum. The time complexity of the solution would be O(n)O(n).

    1
    int main()
    2
    {
    3
    int n, k;
    4
    cin >> n >> k;
    5
    6
    vector<int> arr(n + 1);
    7
    long long sum = 0;
    8
    for (int i = 1; i <= n; i++)
    9
    {
    10
    cin >> arr[i];
    11
    sum += arr[i];
    12
    }
    13
    14
    vector<long long> dp(n + 1), g(n + 1);
    15
    deque<int> dq;
    16
    for (int i = 1; i <= k; i++)
    17
    {
    18
    dp[i] = 0;
    19
    g[i] = dp[i - 1] + arr[i];
    20
    21
    while (!dq.empty() && g[dq.back()] >= g[i])
    22
    dq.pop_back();
    23
    dq.push_back(i);
    24
    }
    25
    26
    for (int i = k + 1; i <= n; i++)
    27
    {
    28
    while (!dq.empty() && i - dq.front() > k)
    29
    dq.pop_front();
    30
    31
    dp[i] = g[dq.front()];
    32
    g[i] = dp[i - 1] + arr[i];
    33
    34
    while (!dq.empty() && g[dq.back()] >= g[i])
    35
    dq.pop_back();
    36
    dq.push_back(i);
    37
    }
    38
    39
    cout << sum - dp[n] << endl;
    40
    }
  6. There are nn cities in a country. You need to start at city ss and end at city tt. Between any two cities, you can either take a plane or a boat. The cost for both of them would be given. You want to plan your journey in such a manner that you change your mode of travel between cities (i.e. from plane to boat, or from boat to plane) at most once in the whole journey. Find the minimum cost of the travel.

    Constraints:

    • 1n1031 \leq n \leq 10^3
    • 1s,tn1 \leq s, t \leq n
    • 1costij1091 \leq cost_{ij} \leq 10^9
    Solution
    1
    int main() {
    2
    int n;
    3
    cin >> n;
    4
    5
    vector<vector<int>> boat(n, vector<int>(n));
    6
    for (int i = 0; i < n; i++)
    7
    for (int j = 0; j < n; j++)
    8
    cin >> boat[i][j];
    9
    10
    vector<vector<int>> plane(n, vector<int>(n));
    11
    for (int i = 0; i < n; i++)
    12
    for (int j = 0; j < n; j++)
    13
    cin >> plane[i][j];
    14
    15
    int s, t;
    16
    cin >> s >> t;
    17
    s--, t--;
    18
    19
    // Node, Last Mode, Flipped Mode
    20
    long long dis[n][2][2];
    21
    for (int i = 0; i < n; i++)
    22
    for (int j = 0; j < 2; j++)
    23
    for (int k = 0; k < 2; k++)
    24
    dis[i][j][k] = 1e18;
    25
    26
    priority_queue<vector<long long>, vector<vector<long long>>, greater<vector<long long>>> pq;
    27
    pq.push({0, s, 0, 0});
    28
    pq.push({0, s, 1, 0});
    29
    dis[s][0][0] = 0;
    30
    dis[s][1][0] = 0;
    31
    32
    while (!pq.empty()) {
    33
    auto top = pq.top();
    34
    pq.pop();
    35
    36
    long long d = top[0], u = top[1], mode = top[2], flipped = top[3];
    37
    if (dis[u][mode][flipped] < d)
    38
    continue;
    39
    40
    for (int v = 0; v < n; v++)
    41
    for (int newMode = 0; newMode < 2; newMode++) {
    42
    long long w = (newMode == 0 ? boat[u][v] : plane[u][v]);
    43
    if (w == -1)
    44
    continue;
    45
    46
    int newFlipped = flipped + (mode != newMode);
    47
    if (newFlipped > 1)
    48
    continue;
    49
    50
    if (dis[v][newMode][newFlipped] > dis[u][mode][flipped] + w) {
    51
    dis[v][newMode][newFlipped] = dis[u][mode][flipped] + w;
    52
    pq.push({dis[v][newMode][newFlipped], v, newMode, newFlipped});
    53
    }
    54
    }
    55
    }
    56
    57
    cout << min({
    58
    dis[t][0][0],
    59
    dis[t][0][1],
    60
    dis[t][1][0],
    61
    dis[t][1][1],
    62
    }) << endl;
    63
    }
  7. You are given an array of length nn. In each step you do the following:

    1. Add the sum of the array to your score.
    2. If the length of the array is 11, the game ends.
    3. You partition the array into two parts, such that both the parts are non-emtpty. You repeat the game with each part individually, and then add the score of both the parts to your score.

    What is the maximum score you can get?

    Constraints:

    • 1n1051 \leq n \leq 10^5
    • 1arr[i]1091 \leq arr[i] \leq 10^9
    Solution

    We will greedily always parition the rest of the subarray and remove the smallest element from the subarray. The time complexity of the solution would be O(nlogn)O(n \log n) due to sorting.

    1
    int main()
    2
    {
    3
    int n;
    4
    cin >> n;
    5
    6
    vector<int> arr(n);
    7
    for (int i = 0; i < n; i++)
    8
    cin >> arr[i];
    9
    10
    sort(arr.begin(), arr.end());
    11
    vector<long long> suf(n);
    12
    suf[n - 1] = arr[n - 1];
    13
    for (int i = n - 2; i >= 0; i--)
    14
    suf[i] = suf[i + 1] + arr[i + 1];
    15
    16
    long long ans = 0;
    17
    for (int i = 0; i < n; i++)
    18
    ans += suf[i];
    19
    20
    cout << ans << "\n";
    21
    }
  8. You are given an array of length nn. Count the number of subarrays of the same whose XORXOR has an even number of divisors.

    Contraints:

    • 1n1051 \leq n \leq 10^5
    • 1arr[i]n1 \leq arr[i] \leq n
    Solution
    1
    int main()
    2
    {
    3
    long long n;
    4
    cin >> n;
    5
    6
    vector<int> arr(n);
    7
    for (int i = 0; i < n; i++)
    8
    cin >> arr[i];
    9
    10
    vector<int> sq;
    11
    for (int i = 0; i * i <= 2 * n; i++)
    12
    sq.push_back(i * i);
    13
    14
    long long ans = n * (n + 1) / 2;
    15
    map<int, int> cnt;
    16
    cnt[0] = 1;
    17
    18
    int pre = 0;
    19
    for (int i = 0; i < n; i++)
    20
    {
    21
    pre ^= arr[i];
    22
    for (int j : sq)
    23
    ans -= cnt[j ^ pre];
    24
    cnt[pre]++;
    25
    }
    26
    27
    cout << ans << "\n";
    28
    }
  9. XOUR

  10. Given a string ss, find the number of substrings of ss that have length atleast ll, length atmost rr, and have less than or equal to kk distinct characters present in them.

    Constraints:

    • 1s1051 \leq |s| \leq 10^5
    • 1lrs1 \leq l \leq r \leq |s|
    • 1k261 \leq k \leq 26
    Solution

    We will use a two-pointer approach to solve this problem. We have calculated an utility that calculates the number of substrings with length at most maxLenmaxLen and having atmost kk distinct characters. Using the same, we can calculate the required quantity in the question. The time complexity of the solution would be O(n)O(n).

    1
    int cntMaxLen(string &s, int maxLen, int k)
    2
    {
    3
    if (k == 0 || maxLen == 0)
    4
    return 0;
    5
    6
    int n = s.size();
    7
    map<char, int> cnt;
    8
    int j = 0;
    9
    cnt[s[0]] = 1;
    10
    11
    int ans = 0;
    12
    for (int i = 0; i < n; i++)
    13
    {
    14
    while (j + 1 < n)
    15
    {
    16
    int curLen = j - i + 1;
    17
    bool lenSatify = curLen + 1 <= maxLen;
    18
    bool szSatisfy = cnt.size() < k || (cnt.find(s[j + 1]) != cnt.end());
    19
    if (lenSatify && szSatisfy)
    20
    {
    21
    j++;
    22
    cnt[s[j]]++;
    23
    }
    24
    else
    25
    break;
    26
    }
    27
    28
    ans += j - i + 1;
    29
    cnt[s[i]]--;
    30
    if (!cnt[s[i]])
    31
    cnt.erase(s[i]);
    32
    }
    33
    34
    return ans;
    35
    }
    36
    37
    int main()
    38
    {
    39
    string s;
    40
    cin >> s;
    41
    42
    int l, r, k;
    43
    cin >> l >> r >> k;
    44
    cout << cntMaxLen(s, r, k) - cntMaxLen(s, l - 1, k);
    45
    }
  11. There is an undirected graph of nn vertices, connected by n1n-1 bidirectional edges. People are standing on each node of the graph connected by a rope inside of this graph. There are 22 ends of the rope: head is at vertex aa and it’s tail is at vertex bb. The people connected by this rope occupy all vertices on the unique simple path between aa and bb. The people want to know if they can reverse their order, meaning that the person standing at the head of the rope needs to move to the node where the rope’s tail is, and the person standing on the tail node needs to move to the node where the rope’s head is. Unfortunately, the people’s movement is restricted to the graph structure.

    In an operation, the person on the head can move to an adjacent vertex not currently occupied. When the person at the head does this each person connected will also move one vertes closer to the head, so that the length of the rope remains unchanged. Similarly, the person standing on the tail vertex can move to an adjacent verter not currently occupied. When the person at tall does this cach person connected will also move one vertex closer to the tail. Determine if it is possible to reverse the people with some sequence of moves.

    Constraints:

    • 1n1051 \leq n \leq 10^5
    • 1a,bn1 \leq a, b \leq n

    This is a restatement of the question The Majestic Brown Snake.

  12. You are monitoring the building density in a district of houses. The district is represented as a number line, where a house can be built at each numbered point on the line if at least one of the neighboring points is not occupied. Initially, there are no houses in the district. You are given queriesqueries, an array of integers representing the locations of new houses in the order in which they will be built. After each house is built, your task is to find the longest segment of contiguous houses in the district. It is guaranteed that all of the house locations in queries are unique and no house was built at a point with existing houses on both left and right adjacent points.

    Constraints:

    • 1queries1051 \leq |queries| \leq 10^5
    • 1queries[i]1091 \leq queries[i] \leq 10^9
    Solution
    1
    int main()
    2
    {
    3
    int q;
    4
    cin >> q;
    5
    6
    set<pair<int, int>> s;
    7
    multiset<int> le;
    8
    int x;
    9
    cin >> x;
    10
    s.insert({x, x});
    11
    le.insert(1);
    12
    cout << 1 << " ";
    13
    14
    for (int i = 1; i < q; i++)
    15
    {
    16
    cin >> x;
    17
    18
    auto itr = s.lower_bound({x, x});
    19
    if (itr != s.end() && (*itr).first == x + 1)
    20
    {
    21
    auto p = *itr;
    22
    le.erase(le.find(p.second - p.first + 1));
    23
    s.erase(itr);
    24
    s.insert({p.first - 1, p.second});
    25
    le.insert({p.second - p.first + 2});
    26
    }
    27
    else if (itr != s.begin() && (*(--itr)).second == x - 1)
    28
    {
    29
    auto p = *itr;
    30
    le.erase(le.find(p.second - p.first + 1));
    31
    s.erase(itr);
    32
    s.insert({p.first, p.second + 1});
    33
    le.insert({p.second - p.first + 2});
    34
    }
    35
    else
    36
    {
    37
    le.insert(1);
    38
    s.insert({x, x});
    39
    }
    40
    41
    cout << *le.rbegin() << " ";
    42
    }
    43
    }

Online Assessment Questions

  1. Checking if the given graph was bipartite.

  2. You are given an array arrarr of length nn. What is the shortest subarray that you must remove from the same so that the sum of the leftover array is divisible by pp?

    Constraints:

    • 1n1051 \leq n \leq 10^5
    • 1arr[i]1091 \leq arr[i] \leq 10^9
    • 1p1091 \leq p \leq 10^9
  3. What is the number of subsets of the numbers [1,2,3,....,n][1, 2, 3, ...., n] such that if xx is present in a subset, then 2x2 \cdot x and 3x3 \cdot x are not present in the same? Return the answer modulo 109+710^9 + 7.

    Constraints:

    • 1n1051 \leq n \leq 10^5
  4. There is a grid of bricks of size N×MN \times M. You make qq attacks on the same. Each attack is represented as (x,y,t)(x, y, t) where you destroy the brick in the row xx and column yy at the time tt. Find the minimum time after which there is atleast a square hole of size k×kk \times k in the wall.

    Constraints:

    • 1n,m1031 \leq n, m \leq 10^3
    • 1q1051 \leq q \leq 10^5
    • 1xn1 \leq x \leq n
    • 1ym1 \leq y \leq m
    • 1t1091 \leq t \leq 10^9

Oracle

Other Campus Questions

  1. You are given two integer xx and yy. You need to find an integer zz such that z2nz \leq 2^n and the value of (xz)(yz)(x \oplus z) \cdot (y \oplus z) is maximum. Here, \oplus denotes the bitwise XOR operation. Return the value of (xz)(yz)(x \oplus z) * (y \oplus z) modulo 109+710^9 + 7.

    Constraints:

    • 1x,y10181 \leq x, y \leq 10^18
    • 1n501 \leq n \leq 50
    Solution

    We will iterate over all the bits of xx and yy and try to set try to set the bit of both the numbers obtained after the XOR to 11. If the same is not possible, we first prefer set the same in the smaller number. The time complexity of the solution would be O(n)O(n).

    int maximumXorProduct(long long a, long long b, int n) {
    for (int bit = n - 1; bit >= 0; bit--)
    {
    int x = (a >> bit) & 1;
    int y = (b >> bit) & 1;
    if (x == y) {
    a |= (1LL << bit);
    b |= (1LL << bit);
    }
    else
    {
    if (a > b)
    swap(a, b);
    a |= (1LL << bit);
    if ((b >> bit) & 1)
    b ^= (1LL << bit);
    }
    }
    long long mod = 1e9 + 7;
    return (a % mod) * (b % mod) % mod;
    }
  2. You are given an undirected connected graph witn nn nodes and mm edges. You first need to construct any traversal of the graph, and store it in array aa. All the nodes must be visited atleast once in this traversal. Then you need to construct another array bb from the array aa, such that bb is a subsequence of aa consiting of only the first occurences of every node. Thus the length of bb would be exactly nn. Find the lexographically maximum sequence bb that can be generated by chosing the array aa optimally.

    Constraints:

    • 1n,m1051 \leq n, m \leq 10^5
    • 1ai,bin1 \leq a_i, b_i \leq n
    Solution
    1
    int main()
    2
    {
    3
    int n, m;
    4
    cin >> n >> m;
    5
    6
    vector<vector<int>> g(n);
    7
    for (int i = 0; i < m; i++)
    8
    {
    9
    int x, y;
    10
    cin >> x >> y;
    11
    g[x - 1].push_back(y - 1);
    12
    g[y - 1].push_back(x - 1);
    13
    }
    14
    15
    vector<int> done(n, 0);
    16
    set<int> candidates;
    17
    vector<int> b;
    18
    19
    b.push_back(n);
    20
    done[n - 1] = 1;
    21
    for (int v : g[n - 1])
    22
    candidates.insert(v);
    23
    24
    while (!candidates.empty())
    25
    {
    26
    auto t = *candidates.rbegin();
    27
    candidates.erase(--candidates.end());
    28
    29
    b.push_back(t + 1);
    30
    done[t] = 1;
    31
    for (int v : g[t])
    32
    if (!done[v])
    33
    candidates.insert(v);
    34
    }
    35
    36
    for (int x : b)
    37
    cout << x << " ";
    38
    }
  3. Count the number of subsequences of string tt in the given string ss. Return the answer modulo 109+710^9 + 7.

    Constraints:

    • 1s,t1031 \leq |s|, |t| \leq 10^3
    Solution
    int main()
    {
    string s, t;
    cin >> s >> t;
    int n = s.size(), m = t.size();
    vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
    for (int i = 0; i <= n; i++)
    dp[i][0] = 1;
    int mod = 1e9 + 7;
    for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
    {
    if (s[i - 1] != t[j - 1])
    dp[i][j] = dp[i - 1][j];
    else
    dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1];
    dp[i][j] %= mod;
    }
    cout << dp[n][m] << "\n";
    }
  4. You are given an integer xx. Find the smallest number greater or equal to xx which has no consecutive one’s in it’s binary representation.

    Constraints:

    • 1x1091 \leq x \leq 10^9
    Solution

    We would iterate from right to left, and maintain a mask to find the occurence of 1111 in the digit. As soon we find the same, we increment the prefix by 11 and replace the suffix of the number with 00000000 \cdots bits.

    int main()
    {
    int x;
    cin >> x;
    int mask = 3, pos = 2;
    while (mask <= x)
    {
    if ((mask & x) == mask)
    {
    x >>= pos;
    x++;
    x <<= pos;
    }
    mask <<= 1;
    pos++;
    }
    cout << x;
    }
  5. Alex is working on a planet where there are NN days in a year. He noticed that his performence on ithi^{th} the day of the year was equal to nums[i]nums[i]. Alex is a hard worker and he wants to come to work for the max number of days that he can. However, he does not want to have a negative total perfonttance at any point in time since his boss will deduct his salary. Help Alex find the major number of days in the year that he can come to the office.

    Constraints:

    • 1N1051 \leq N \leq 10^5
    • 109nums[i]109-10^9 \leq nums[i] \leq 10^9
    Solution
    int main() {
    int n;
    cin >> n;
    vector<int> arr(n);
    for (int i = 0; i < n; i++)
    cin >> arr[i];
    long long sum = 0;
    priority_queue<int, vector<int>, greater<int>> pq;
    int ans = 0;
    for (int i = 0; i < n; i++) {
    if (arr[i] >= 0) {
    sum += arr[i];
    ans++;
    continue;
    }
    if (sum + arr[i] >= 0) {
    sum += arr[i];
    pq.push(arr[i]);
    ans++;
    } else if (!pq.empty() && pq.top() < arr[i]) {
    sum -= pq.top();
    sum += arr[i];
    pq.pop();
    pq.push(arr[i]);
    }
    }
    cout << ans << endl;
    }
  6. You are given an array arrarr. In one operations, you are required to choose a range [l,r][l, r] such that it has not been chosen previously, and then add the value of max(arr[l]...,arr[r])max(arr[l] ..., arr[r]) to your score. What is the maximum score you can obtain after performing at max kk operations?

    Constraints:

    • 1n1051 \leq n \leq 10^5
    • 1kmin(109,n(n+1)2)1 \leq k \leq min(10^9, \frac{n (n + 1)}{2})
    • 1arr[i]1091 \leq arr[i] \leq 10^9
    Solution
    1
    int main()
    2
    {
    3
    long long n, k;
    4
    cin >> n >> k;
    5
    6
    vector<int> arr(n);
    7
    for (int i = 0; i < n; i++)
    8
    cin >> arr[i];
    9
    10
    vector<int> nxtGreater(n, n);
    11
    stack<int> st;
    12
    for (int i = 0; i < n; i++)
    13
    {
    14
    while (!st.empty() && arr[i] > arr[st.top()])
    15
    {
    16
    nxtGreater[st.top()] = i;
    17
    st.pop();
    18
    }
    19
    st.push(i);
    20
    }
    21
    while (!st.empty())
    22
    st.pop();
    23
    24
    vector<int> prevGreater(n, -1);
    25
    for (int i = n - 1; i >= 0; i--)
    26
    {
    27
    while (!st.empty() && arr[i] >= arr[st.top()])
    28
    {
    29
    prevGreater[st.top()] = i;
    30
    st.pop();
    31
    }
    32
    st.push(i);
    33
    }
    34
    35
    vector<pair<long long, long long>> ele;
    36
    for (int i = 0; i < n; i++)
    37
    {
    38
    long long cnt = (i - prevGreater[i]) * (nxtGreater[i] - i);
    39
    ele.push_back({arr[i], cnt});
    40
    }
    41
    sort(ele.begin(), ele.end());
    42
    reverse(ele.begin(), ele.end());
    43
    44
    long long ans = 0, mod = 1e9 + 7;
    45
    for (auto &[x, cnt] : ele)
    46
    {
    47
    long long ops = min(cnt, k);
    48
    k -= ops;
    49
    ans += x * ops;
    50
    ans %= mod;
    51
    if (k == 0)
    52
    break;
    53
    }
    54
    55
    cout << ans << "\n";
    56
    }
  7. You are given a string ss. Find the length of the minimum substring of ss that must be removed from the same, so that the remaining string can be permuted to form a palindrome. String ss only consists of lowercase English alphabets.

    Constraints:

    • 1s1051 \leq |s| \leq 10^5
    Solution
    1
    int main()
    2
    {
    3
    string s;
    4
    cin >> s;
    5
    6
    int n = s.size();
    7
    vector<int> sufMask(n);
    8
    sufMask[n - 1] = (1 << (s[n - 1] - 'a'));
    9
    for (int i = n - 2; i >= 0; i--)
    10
    sufMask[i] = sufMask[i + 1] ^ (1 << (s[i] - 'a'));
    11
    12
    vector<int> tarMasks = {0};
    13
    for (int j = 0; j < 26; j++)
    14
    tarMasks.push_back(1 << j);
    15
    16
    unordered_map<int, int> idx;
    17
    idx[0] = -1;
    18
    int ans = n;
    19
    int pre = 0;
    20
    21
    for (int i = 0; i < n; i++)
    22
    {
    23
    pre ^= (1 << (s[i] - 'a'));
    24
    for (auto t : tarMasks)
    25
    {
    26
    t = t ^ sufMask[i];
    27
    if (idx.find(t) != idx.end())
    28
    ans = min(ans, i - idx[t] - 1);
    29
    }
    30
    31
    idx[pre] = i;
    32
    }
    33
    34
    cout << ans << "\n";
    35
    }
  8. You are given nn points on a grid. Calculate the area of the minimum square that encloses at-least kk of the points in the grid. The points that lie on the boundary of the square are not counted as to be enclosed in the same.

    Constraints:

    • 1n1001 \leq n \leq 100
    • 1kn1 \leq k \leq n
    • 109x,y109-10^9 \leq x, y \leq 10^9
    Solution
    1
    int main()
    2
    {
    3
    int n;
    4
    cin >> n;
    5
    6
    vector<pair<int, int>> pts(n);
    7
    for (int i = 0; i < n; i++)
    8
    cin >> pts[i].first >> pts[i].second;
    9
    10
    int k;
    11
    cin >> k;
    12
    13
    int ans = 1e9;
    14
    15
    for (int i = 0; i < n; i++)
    16
    for (int j = i + k - 1; j < n; j++)
    17
    {
    18
    int xr = pts[j].first - pts[i].first + 2;
    19
    20
    vector<int> y;
    21
    for (int t = i; t <= j; t++)
    22
    y.push_back(pts[t].second);
    23
    sort(y.begin(), y.end());
    24
    25
    int m = y.size();
    26
    for (int t = 0; t + k - 1 < m; t++)
    27
    {
    28
    int yr = y[t + k - 1] - y[t] + 2;
    29
    ans = min(ans, max(yr, xr));
    30
    }
    31
    }
    32
    33
    cout << (long long)ans * (long long)ans << "\n";
    34
    }
  9. Maximise the String

  10. You are given a tree of nn nodes. You need to colour the nodes of the tree with mm colours, such that no two adjacent nodes, as well as two nodes that are adjacent to a common city have the same colour. Output the number of colourings of the graph modulo 109+710^9 + 7.

    Constraints:

    • 1n1051 \leq n \leq 10^5
    • 1m1051 \leq m \leq 10^5
    Solution
    1
    long long MOD = 1e9 + 7;
    2
    3
    long long binPow(long long a, long long b)
    4
    {
    5
    a %= MOD;
    6
    long long res = 1;
    7
    8
    while (b)
    9
    {
    10
    if (b & 1)
    11
    {
    12
    res = res * a;
    13
    res %= MOD;
    14
    }
    15
    a *= a;
    16
    a %= MOD;
    17
    b >>= 1;
    18
    }
    19
    20
    return res;
    21
    }
    22
    23
    int main()
    24
    {
    25
    long long n, m;
    26
    cin >> n >> m;
    27
    28
    vector<vector<int>> g(n);
    29
    for (int i = 0; i < n - 1; i++)
    30
    {
    31
    int u, v;
    32
    cin >> u >> v;
    33
    g[u - 1].push_back(v - 1);
    34
    g[v - 1].push_back(u - 1);
    35
    }
    36
    37
    vector<long long> fac(m + 1);
    38
    fac[0] = 1;
    39
    for (long long i = 1; i <= m; i++)
    40
    {
    41
    fac[i] = i * fac[i - 1];
    42
    fac[i] %= MOD;
    43
    }
    44
    45
    vector<long long> inv(m + 1);
    46
    for (int i = 0; i <= m; i++)
    47
    inv[i] = binPow(fac[i], MOD - 2);
    48
    49
    auto nCr = [&](int n, int r) -> long long
    50
    {
    51
    if (r > n)
    52
    return 0;
    53
    54
    long long dr = (inv[r] * inv[n - r]) % MOD;
    55
    return (fac[n] * dr) % MOD;
    56
    };
    57
    58
    function<long long(int, int, int)> dfs = [&](int u, int p, int d) -> long long
    59
    {
    60
    int cnt = 0;
    61
    62
    long long ways = 1;
    63
    for (int v : g[u])
    64
    {
    65
    if (v == p)
    66
    continue;
    67
    cnt++;
    68
    ways *= dfs(v, u, d + 1);
    69
    ways %= MOD;
    70
    }
    71
    72
    if (d == 0)
    73
    {
    74
    long long w = (nCr(m - 1, cnt) * fac[cnt]) % MOD;
    75
    return (w * ways) % MOD;
    76
    }
    77
    78
    long long w = (nCr(m - 2, cnt) * fac[cnt]) % MOD;
    79
    return (w * ways) % MOD;
    80
    };
    81
    82
    long long ans = m * dfs(0, -1, 0);
    83
    cout << ans % MOD << "\n";
    84
    }
  1. 2-3 Trees are a type of balanced search tree data structure that is used to store sorted data and allows for search, sequential access, insertions, and deletions in logarithmic time. A 2-3 tree is a B-tree of order 3.

    • They are always balanced and support search, insert, and delete operations in O(logn)O(\log n) time, which can take upto O(n)O(n) time in a binary search tree.
    • Every non-leaf node in a 2-3 tree has either two children and one data element or three children and two data elements. All the leaves of the tree are at the same level.
    • They require more space than binary search trees as the internal nodes do not store the keys and associated data, and are for internal organization only.
  2. ARP or Address Resolution Protocol is a protocol used for mapping an IP address to a MAC address that is recognized in the local network. The protocol is used when information is needed to send a packet to a device on the same network. It is a layer 22 protocol.

  3. /etc/passwd is a text file that contains information about the users on a Unix-like operating system. It is used to store the essential information required during login. The file contains the user’s username, user ID, group ID, home directory, and shell.

  4. /etc/hosts is a text file that maps hostnames to IP addresses. It is used to resolve hostnames to IP addresses when DNS is not available. The file is used by the operating system to map hostnames to IP addresses before querying a DNS server.

  5. CAP or Consistency, Availability, and Partition Tolerance is a theorem that states that it is impossible for a distributed system to simultaneously provide all three guarantees. The theorem is used to describe the trade-offs that must be made when designing distributed systems.

  6. The latest long term release of Oracle Database is Oracle Database 23ai.

  7. The interrupt defined for system calls in Unix is 128 (0x80). The Linux kernel registers an interrupt handler named ia32_syscall for this interrupt.

Online Assessment Questions

The MCQs were exactly repeated from other campus and previous year questions. Everyone had one different coding question, but the same was of easy to medium difficulty level on LeetCode.

  1. You are given a weighted undirected graph of nn nodes. You need to start from node 11, end at node nn, and visit the nodes xx and yy in between your journey (in the same order). You are allowed to visit the same nodes multiple times. What is the minimum distance of the total journey?

    Constraints:

    • 1n1051 \leq n \leq 10^5

Confluent

Online Assessment Questions

  1. You are given a string of length nn consisiting of lowercase English letters. You need to count the number of substrings of ss such that the substring only consists of vowels, and all the vowels are present in the same atleast once.

    Constraints:

    • 1n1051 \leq n \leq 10^5
  2. Same question as 44 from the Online Assessment Questions from Pace Stock Broking

  3. A lottery ticket is present by the number nn, and the value of the lottery ticket is equal to the sum of the digits of nn. In a lottery sessions, all the ticket numbers between lowLimitlowLimit and highLimithighLimit (both inclusive) have been sold. A ticker is considered a winner if the value of the ticket is equal to the value decided by the organizers. Count the number of values that the organizers can choose so that the number of winners in the draw is maximized. Also return the number of people that would be winning the lottery in the said value is chosen.

    Constraints:

    • 1lowLimithighLimit10181 \leq lowLimit \leq highLimit \leq 10^{18}

Amazon

Online Assessment Questions

  1. There are two arrays of length nn, namely aa and bb. In one operation, you can choose two indexes ii and jj, and decrement a[i]a[i] by 11 and increment a[j]a[j] by 11. This operation can only be performed if a[i]a[i] remains non-negative after the operation. You need to find the maximum number of indexes that can be made equal in both the arrays by performing the operations.

    Constraints:

    • 1n1051 \leq n \leq 10^5
    • 1a[i],b[i]1091 \leq a[i], b[i] \leq 10^9
    Solution
    1
    int main()
    2
    {
    3
    int n;
    4
    cin >> n;
    5
    6
    vector<int> a(n), b(n);
    7
    8
    int sum = 0;
    9
    for (int i = 0; i < n; i++)
    10
    {
    11
    cin >> a[i];
    12
    sum += a[i];
    13
    }
    14
    15
    for (int i = 0; i < n; i++)
    16
    cin >> b[i];
    17
    sort(b.begin(), b.end());
    18
    19
    int ans = 0, curSum = 0;
    20
    for (int i = 0; i < n; i++)
    21
    {
    22
    curSum += b[i];
    23
    if (curSum <= sum)
    24
    ans = i + 1;
    25
    }
    26
    if (curSum != sum && ans == n)
    27
    ans--;
    28
    29
    cout << ans << "\n";
    30
    }
  2. You are given an array arrarr. In one operation, you can decrease the value of one element by pp units, and the value of all the other elements by qq units. If is gauranteed that p>qp > q. What is the minimum number of operations to make the value of all the elements of the array less than or equal to 00?

    Constraints:

    • 1n1051 \leq n \leq 10^5
    • 1arr[i]1091 \leq arr[i] \leq 10^9
    • 1p,q1091 \leq p, q \leq 10^9
    1
    bool check(int tot, vector<int> &arr, int p, int q)
    2
    {
    3
    int cnt = 0;
    4
    5
    for (auto x : arr)
    6
    {
    7
    // p * cnt + q * (tot - cnt) >= x
    8
    // cnt * (p - q) >= x - q * tot
    9
    int num = x - q * tot;
    10
    int den = p - q;
    11
    cnt += (num + den - 1) / den;
    12
    if (cnt > tot)
    13
    return 0;
    14
    }
    15
    16
    return 1;
    17
    }
    18
    19
    int main()
    20
    {
    21
    int n;
    22
    cin >> n;
    23
    24
    vector<int> arr(n);
    25
    for (int i = 0; i < n; i++)
    26
    cin >> arr[i];
    27
    28
    int p, q;
    29
    cin >> p >> q;
    30
    31
    int l = 0, r = 1e9;
    32
    int ans;
    33
    while (l <= r)
    34
    {
    35
    int m = (l + r) / 2;
    36
    if (check(m, arr, p, q))
    37
    {
    38
    ans = m;
    39
    r = m - 1;
    40
    }
    41
    else
    42
    l = m + 1;
    43
    }
    44
    45
    cout << ans << "\n";
    46
    }
  3. You are given nn base strings. Then you are mm strings as queries. For each query, you need to determine if there exists atleast one string from the provided nn strings such that the following conditions hold:

    • The length of the query string is equal to the length of the base string.
    • The query string differs from the base string in exactly one position.

    Constraints:

    • 1n,m31031 \leq n, m \leq 3 \cdot 10^3
    • 1base[i],query[i]1031 \leq |base[i]|, |query[i]| \leq 10^3
    Solution

    We will make use of string hashing to solve this problem.

    1
    class Hasher
    2
    {
    3
    public:
    4
    long long p;
    5
    long long mod;
    6
    vector<long long> pow;
    7
    8
    Hasher(int p, long long mod, int maxLen) : p(p), mod(mod)
    9
    {
    10
    pow.resize(maxLen + 1);
    11
    pow[0] = 1;
    12
    for (int i = 1; i <= maxLen; i++)
    13
    pow[i] = (pow[i - 1] * p) % mod;
    14
    }
    15
    16
    long long getHash(string &s)
    17
    {
    18
    long long hash = 0;
    19
    for (int i = 0; i < s.size(); i++)
    20
    {
    21
    hash += (long long)(s[i] - 'a' + 1) * pow[i];
    22
    hash %= mod;
    23
    }
    24
    25
    return hash;
    26
    }
    27
    28
    vector<long long> getHashPre(string &s)
    29
    {
    30
    int n = s.size();
    31
    vector<long long> hash(n);
    32
    for (int i = 0; i < n; i++)
    33
    {
    34
    hash[i] = (i == 0 ? 0 : hash[i - 1]) + (long long)(s[i] - 'a' + 1) * pow[i];
    35
    hash[i] %= mod;
    36
    }
    37
    38
    return hash;
    39
    }
    40
    41
    vector<long long> getHashSuf(string &s)
    42
    {
    43
    int n = s.size();
    44
    vector<long long> hash(n);
    45
    for (int i = n - 1; i >= 0; i--)
    46
    {
    47
    hash[i] = (i == n - 1 ? 0 : hash[i + 1]) + (long long)(s[i] - 'a' + 1) * pow[i];
    48
    hash[i] %= mod;
    49
    }
    50
    51
    return hash;
    52
    }
    53
    };
    54
    55
    int main()
    56
    {
    57
    int n;
    58
    cin >> n;
    59
    60
    int MAXLEN = 1001;
    61
    62
    Hasher h(31, 1e15 + 7, MAXLEN);
    63
    vector<set<long long>> present(MAXLEN + 1);
    64
    65
    for (int i = 0; i < n; i++)
    66
    {
    67
    string s;
    68
    cin >> s;
    69
    present[s.size()].insert(h.getHash(s));
    70
    }
    71
    72
    int m;
    73
    cin >> m;
    74
    while (m--)
    75
    {
    76
    string s;
    77
    cin >> s;
    78
    auto hashPre = h.getHashPre(s), hashSuf = h.getHashSuf(s);
    79
    80
    bool found = 0;
    81
    for (int i = 0; i < s.size(); i++)
    82
    {
    83
    long long hash = (i == 0 ? 0 : hashPre[i - 1]) + (i == s.size() - 1 ? 0 : hashSuf[i + 1]);
    84
    hash %= h.mod;
    85
    for (char c = 'a'; c <= 'z'; c++)
    86
    {
    87
    if (c == s[i])
    88
    continue;
    89
    90
    long long newHash = hash + (long long)(c - 'a' + 1) * h.pow[i];
    91
    newHash %= h.mod;
    92
    if (present[s.size()].find(newHash) != present[s.size()].end())
    93
    {
    94
    found = 1;
    95
    break;
    96
    }
    97
    }
    98
    99
    if (found)
    100
    break;
    101
    }
    102
    103
    cout << (found ? "YES" : "NO") << "\n";
    104
    }
    105
    }
  4. Building a Fence

  5. You are given an array representing multiple intervals (l,r)(l, r). You need to count the number of intersections between all the pairs of the intersections.

    Solution
    1
    int main() {
    2
    int n;
    3
    cin >> n;
    4
    5
    vector<pair<int, int>> arr(n);
    6
    for (int i = 0; i < n; i++)
    7
    cin >> arr[i].first >> arr[i].second;
    8
    sort(arr.begin(), arr.end());
    9
    10
    priority_queue<int, vector<int>, greater<int>> pq;
    11
    int ans = 0;
    12
    13
    for (int i = 0; i < n; i++) {
    14
    while (!pq.empty() && pq.top() < arr[i].first)
    15
    pq.pop();
    16
    ans += pq.size();
    17
    pq.push(arr[i].second);
    18
    }
    19
    20
    cout << ans << endl;
    21
    }
  6. You are given an array representing multiple intervals (l,r)(l, r). For each interval, determine the number of intervals that the same intersects with. Two intervals are said to intersect if they have atleast one common element.

    Solution
    1
    vector<int> countIntersections(vector<pair<int, int>> &pts)
    2
    {
    3
    int n = pts.size();
    4
    5
    vector<vector<int>> arr;
    6
    for (int i = 0; i < n; i++)
    7
    arr.push_back({pts[i].first, pts[i].second, i});
    8
    sort(arr.begin(), arr.end());
    9
    10
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    11
    vector<int> ans(n);
    12
    13
    for (int i = 0; i < n; i++)
    14
    {
    15
    while (!pq.empty() && pq.top().first < arr[i][0])
    16
    {
    17
    auto [_, idx] = pq.top();
    18
    pq.pop();
    19
    // Remove extraneous assumed intersections
    20
    ans[idx] -= n - i;
    21
    }
    22
    23
    int idx = arr[i][2];
    24
    ans[idx] += pq.size(); // Intersections before me
    25
    ans[idx] += n - i - 1; // Intersections after me (assumed to be all)
    26
    pq.push({arr[i][1], idx});
    27
    }
    28
    29
    return ans;
    30
    }

Seimens

Other Campus Questions

  1. Bob developed a search game where he stores NN special sequences in a database. The sequences are stored in an array of strings called “games” and each sequence is of size MM. Afterwards, Bob asks a bot QQ queries. When a query is made, the bot searches the database for any previously stored games. A special sequence is provided in each query. The special sequence is written as aa where a1,a2,...aka_1, a_2, ... a_k the initial sequence and the terms ak+1,ak+2,....ama_{k+1}, a_{k+2}, .... a_m are all 1-1 and must be ignored when processing the input. The bot’s task is to find the number of games stored in the database that have the provided sequence as a prefix.

    Constraints:

    • 1n,m1031 \leq n, m \leq 10^3
    • 1q51031 \leq q \leq 5 \cdot 10^3
    • 1games[i]2001 \leq games[i] \leq 200
    Solution
    1
    class Node
    2
    {
    3
    public:
    4
    vector<int> ch;
    5
    int cnt;
    6
    7
    Node()
    8
    {
    9
    ch.assign(201, -1);
    10
    cnt = 0;
    11
    }
    12
    };
    13
    14
    class Trie
    15
    {
    16
    int root;
    17
    vector<Node> nodes;
    18
    19
    public:
    20
    Trie()
    21
    {
    22
    nodes.push_back(Node());
    23
    root = 0;
    24
    }
    25
    26
    void add(vector<int> &arr)
    27
    {
    28
    int r = root;
    29
    for (int nxt : arr)
    30
    {
    31
    if (nxt == -1)
    32
    return;
    33
    34
    int u = nodes[r].ch[nxt];
    35
    if (u == -1)
    36
    {
    37
    u = nodes.size();
    38
    nodes.push_back(Node());
    39
    nodes[r].ch[nxt] = u;
    40
    }
    41
    42
    r = u;
    43
    nodes[r].cnt++;
    44
    }
    45
    }
    46
    47
    int get(vector<int> &arr)
    48
    {
    49
    int r = root;
    50
    for (int nxt : arr)
    51
    {
    52
    if (nxt == -1)
    53
    return nodes[r].cnt;
    54
    55
    int u = nodes[r].ch[nxt];
    56
    if (u == -1)
    57
    return 0;
    58
    r = u;
    59
    }
    60
    61
    return nodes[r].cnt;
    62
    }
    63
    };
    64
    65
    int main()
    66
    {
    67
    int n, m;
    68
    cin >> n >> m;
    69
    70
    Trie trie;
    71
    for (int i = 0; i < n; i++)
    72
    {
    73
    vector<int> arr(m);
    74
    for (int j = 0; j < m; j++)
    75
    cin >> arr[j];
    76
    trie.add(arr);
    77
    }
    78
    79
    int q;
    80
    cin >> q;
    81
    while (q--)
    82
    {
    83
    vector<int> arr(m);
    84
    for (int i = 0; i < m; i++)
    85
    cin >> arr[i];
    86
    cout << trie.get(arr) << endl;
    87
    }
    88
    }
  2. Two players, Player 11 and Player 22, are playing a game on a 2D2D board. The board has an origin cell at (0,0)(0, 0) and extends infinitely in positive coordinates. There are NN stones placed on the board, each located in a cell (X,Y)(X, Y). Each player can move a stone from it’s current position (a,b)(a, b) to a new cell (ap,b)(a - p, b) or (a,bp)(a, b - p) (they can’t be placed on negative coordinates). The only requirement is that pp must be a prime number, and the new cell has to be within the board’s valid range. If a player cannot move any stone, they lose the game.

    Both players are strategic in their moves, and Player 11 goes first. Which player wins the game? If it’s Player 11, print A, otherwise, print B.

    Constraints:

    • 1t101 \leq t \leq 10
    • 1n1051 \leq n \leq 10^5
    • 0X,Y2000 \leq X, Y \leq 200
    Solution
    1
    vector<int> primes;
    2
    vector<vector<int>> g;
    3
    4
    int getGrundy(int x, int y)
    5
    {
    6
    if (g[x][y] != -1)
    7
    return g[x][y];
    8
    9
    set<int> s;
    10
    for (int p : primes)
    11
    {
    12
    if (p > x && p > y)
    13
    break;
    14
    if (p <= x)
    15
    s.insert(getGrundy(x - p, y));
    16
    if (p <= y)
    17
    s.insert(getGrundy(x, y - p));
    18
    }
    19
    20
    int mex = 0;
    21
    while (s.find(mex) != s.end())
    22
    mex++;
    23
    return g[x][y] = mex;
    24
    }
    25
    26
    void solve()
    27
    {
    28
    int n;
    29
    cin >> n;
    30
    31
    int xor_val = 0;
    32
    for (int i = 0; i < n; i++)
    33
    {
    34
    int x, y;
    35
    cin >> x >> y;
    36
    xor_val ^= getGrundy(x, y);
    37
    }
    38
    39
    cout << (xor_val ? "A" : "B") << endl;
    40
    }
    41
    42
    int main()
    43
    {
    44
    int t;
    45
    cin >> t;
    46
    47
    // Calculate primes
    48
    for (int i = 2; i <= 199; i++)
    49
    {
    50
    int j = 2;
    51
    bool isPrime = 1;
    52
    for (int k = 2; k * k <= i; k++)
    53
    if (i % k == 0)
    54
    {
    55
    isPrime = 0;
    56
    break;
    57
    }
    58
    if (isPrime)
    59
    primes.push_back(i);
    60
    }
    61
    62
    // Initiliase grundy values
    63
    g.assign(201, vector<int>(201, -1));
    64
    65
    while (t--)
    66
    solve();
    67
    }
  3. Alice and Bob have integers represented by arrays AA and BB respectively of length nn each. For some integer value they want to achieve the sum i=0i=n1A[i]B[i]\sum_{i = 0}^{i = n - 1} A[i] \cdot B[i] on their respective array to be at most KK. Both are allowed to do some operations. In a single operation, choose any index element xx and replace it with floor(x/2)floor(x/2). Determine who can achieve the sum at most KK in a minimum number of operations. Print Alice if she can achieve the required sum in less number of operations than Bob, or print Bob if he can achieve the required sum in less number of operations than Alice. Print Tie in the case of a tie.

    • If Alice starts doing operations, Bob waits for her to finish, and vice versa.
    • Both Alice and Bob start with the original array AA and array BB in their respective turn.
    • 00 based indexing is followed.

    Constraints:

    • 1t101 \leq t \leq 10
    • 1n1051 \leq n \leq 10^5
    • 1A[i],B[i]1061 \leq A[i], B[i] \leq 10^6
    • 1k10181 \leq k \leq 10^{18}
    Solution
    1
    vector<long long> reduce(vector<long long> arr, vector<long long> &b, int ops)
    2
    {
    3
    priority_queue<pair<long long, int>> pq;
    4
    for (int i = 0; i < arr.size(); i++)
    5
    pq.push({arr[i] * b[i] - (arr[i] / 2) * b[i] , i});
    6
    7
    while (ops-- && !pq.empty())
    8
    {
    9
    auto [_, idx] = pq.top();
    10
    pq.pop();
    11
    arr[idx] /= 2;
    12
    13
    long long nxt = arr[idx] * b[idx];
    14
    if (nxt)
    15
    pq.push({nxt - (arr[idx] / 2) * b[idx], idx});
    16
    }
    17
    18
    return arr;
    19
    }
    20
    21
    int getOps(vector<long long> &a, vector<long long> &b, long long mx)
    22
    {
    23
    int n = a.size();
    24
    int l = 0, r = 24 * n;
    25
    int ans = -1;
    26
    27
    while (l <= r)
    28
    {
    29
    int m = (l + r) / 2;
    30
    31
    auto arr = reduce(a, b, m);
    32
    long long score = 0;
    33
    for (int i = 0; i < n; i++)
    34
    {
    35
    score += arr[i] * b[i];
    36
    if (score >= mx)
    37
    break;
    38
    }
    39
    40
    if (score <= mx)
    41
    {
    42
    ans = m;
    43
    r = m - 1;
    44
    }
    45
    else
    46
    l = m + 1;
    47
    }
    48
    49
    return ans;
    50
    }
    51
    52
    int main()
    53
    {
    54
    int t;
    55
    cin >> t;
    56
    57
    while (t--)
    58
    {
    59
    int n;
    60
    cin >> n;
    61
    62
    vector<long long> a(n), b(n);
    63
    for (int i = 0; i < n; i++)
    64
    cin >> a[i];
    65
    for (int i = 0; i < n; i++)
    66
    cin >> b[i];
    67
    68
    long long mx;
    69
    cin >> mx;
    70
    71
    int op1 = getOps(a, b, mx), op2 = getOps(b, a, mx);
    72
    if (op1 < op2)
    73
    cout << "Alice\n";
    74
    else if (op1 > op2)
    75
    cout << "Bob\n";
    76
    else
    77
    cout << "Tie\n";
    78
    }
    79
    }

Online Assessment Questions

There were 44 sections in the test and each section had it’s own time limit of approximately 2020 minutes. The sections were as follows:

  1. Mental Ability & Aptitude:

    • 20 Questions in 20 minutes.
    • Typical questions on probability, permutations, combinations, and series that required a good amount of calculations.
  2. Digital Logic

    • 16 Questions in 25 minutes.
    • Topics like Verilog, KMap, Boolean Algebra, Multiplexers, Decoders and Number Representation were covered.
  3. Software Engineering

    • 16 Questions in 20 minutes.
    • A lot of questions were based on C++ and OOPS.
    • Most of the questions were based on guessing the output or the error in the code.
  4. Coding

    • 2 Questions in 20 minutes.
    • You are given a graph with nn nodes and mm edges. You need to find the number of pairs of nodes in the graph such that the two nodes do not belong to the same connected component.
    • You are given an integer array of even length. The rank of the biggest element of the array is 11, the rank of the second biggest element is 22, and so on. You need to find the absolute difference between the sum of the ranks of the elements in the first half of the array and the sum of the ranks of the elements in the second half of the array.

Walmart

Other Campus Questions

  1. You are given a box of crayons with different colors represented by different alphabets. In one operation, you can remove several continuous crayons of the same color. You may perform this operation several times until the box is empty. Each time you can choose the crayon set, they must be continuous and of the same colors (the set of xx crayons, x1x \geq 1). After removing them, you will get xxx \cdot x points. You are given an integer NN where NN denotes the total number of crayons in the box. You are also given an array colors denoting the NN colors in the box where each color is represented by an English alphabet. Return the maximum points, you can get in the given scenario.

    Constraints:

    • 1n601 \leq n \leq 60
    Solution

    The problem can be solved using dynamic programming. Let dp[i][j][cnt]dp[i][j][cnt] denotes the maximum score that we can achieve by removing the crayons from ii to jj and we have cntcnt continuous crayons of the same color as the ithi^{th} crayon. Refer to the solution to see the transition. Careful handling of states is needed to avoid wrong memoization. The time complexity of the solution is O(n4)O(n^4).

    1
    using vi = vector<int>;
    2
    using vvi = vector<vi>;
    3
    4
    int solve(int l, int r, int cnt, vector<vvi> &dp, vector<char> &arr)
    5
    {
    6
    if (l > r)
    7
    return 0;
    8
    if (dp[l][r][cnt] != -1)
    9
    return dp[l][r][cnt];
    10
    11
    int orgL = l, orgCnt = cnt;
    12
    while (l + 1 <= r && arr[l + 1] == arr[l])
    13
    {
    14
    ++l;
    15
    ++cnt;
    16
    }
    17
    18
    int score = cnt * cnt + solve(l + 1, r, 1, dp, arr);
    19
    for (int j = l + 1; j <= r; j++)
    20
    if (arr[l] == arr[j])
    21
    {
    22
    int newScore = solve(l + 1, j - 1, 1, dp, arr) + solve(j, r, cnt + 1, dp, arr);
    23
    score = max(score, newScore);
    24
    }
    25
    26
    return dp[orgL][r][orgCnt] = score;
    27
    }
    28
    29
    int main()
    30
    {
    31
    int n;
    32
    cin >> n;
    33
    34
    vector<char> arr(n);
    35
    for (int i = 0; i < n; i++)
    36
    cin >> arr[i];
    37
    38
    if (n == 1) {
    39
    cout << 1 << "\n";
    40
    return 0;
    41
    }
    42
    43
    vector<vvi> dp(n, vvi(n, vi(n, -1)));
    44
    cout << solve(0, n - 1, 1, dp, arr);
    45
    46
    return 0;
    47
    }
  2. You are given an array arrarr of size NN. The power of the array represents the sum of the values that you obtain after performing the described operations for NN times. Your task is to delete the array by performing the following operations in exactly NN turns.

    • For any turniturn_i; where 1iN1 \leq i \leq N, delete either of the end (first or last elements of remaining array).
    • Before deleting that element (let’s say at index KK), it contributes to the sum of the values as arr[K]turni+SViarr[K] \cdot turn_i + SV_i to the power of the array. Here turniturn_i, represents the number of turn in which you are performing the operation, and SViSV_i represents the value of the maximum element that is present in the remaining array before the turn is performed.

    You are required to perform this in such a way that you maximize the value of the power of the array. Print the maximum value of the power that can be obtained after the array is completely deleted.

    Constraints:

    • 1n1031 \leq n \leq 10^3
    • 1arr[i]1091 \leq arr[i] \leq 10^9
    Solution
    1
    void solve()
    2
    {
    3
    int n;
    4
    cin >> n;
    5
    vector<long long> arr(n);
    6
    for (int i = 0; i < n; i++)
    7
    cin >> arr[i];
    8
    9
    vector<vector<long long>> mx(n, vector<long long>(n));
    10
    for (int i = 0; i < n; i++)
    11
    {
    12
    mx[i][i] = arr[i];
    13
    for (int j = i + 1; j < n; j++)
    14
    mx[i][j] = max(mx[i][j - 1], arr[j]);
    15
    }
    16
    17
    vector<vector<long long>> dp(n, vector<long long>(n, -1));
    18
    19
    function<long long(int, int)> get = [&](int f, int b) -> long long
    20
    {
    21
    long long turn = f + b + 1;
    22
    if (turn > n)
    23
    return 0;
    24
    if (dp[f][b] != -1)
    25
    return dp[f][b];
    26
    27
    long long ans = arr[f] * turn + mx[f][n - 1 - b] + get(f + 1, b);
    28
    ans = max(arr[n - b - 1] * turn + mx[f][n - 1 - b] + get(f, b + 1), ans);
    29
    30
    return dp[f][b] = ans;
    31
    };
    32
    33
    cout << get(0, 0) <<d "\n";
    34
    }
    35
    36
    int main()
    37
    {
    38
    int t;
    39
    cin >> t;
    40
    while (t--)
    41
    solve();
    42
    return 0;
    43
    }
  3. Count the sum of XOR values of all the subarrays of the provided array arrarr with length nn. Provide the sum of the XOR values modulo 109+710^9 + 7.

    Constraints:

    • 1n1051 \leq n \leq 10^5
    • 1arr[i]1091 \leq arr[i] \leq 10^9
    Solution
    1
    int main() {
    2
    int n;
    3
    cin >> n;
    4
    5
    vector<int> arr(n);
    6
    for (int i = 0; i < n; i++)
    7
    cin >> arr[i];
    8
    9
    10
    long long MOD = 1e9 + 7;
    11
    long long ans = 0;
    12
    13
    for (int bit = 0; bit < 31; bit++) {
    14
    // cntOdd -> Count of subarrays with odd number of 1's starting at index 0
    15
    // odd -> Current count of 1's in the subarray
    16
    int cntOdd = 0, odd = 0;
    17
    long long cnt = 0;
    18
    19
    for (int i = 0; i < n; i++) {
    20
    if (arr[i] & (1 << bit))
    21
    odd ^= 1;
    22
    if (odd)
    23
    cntOdd++;
    24
    }
    25
    26
    for (int i = 0; i < n; i++) {
    27
    cnt += cntOdd;
    28
    if (arr[i] & (1 << bit))
    29
    cntOdd = n - i - cntOdd;
    30
    }
    31
    32
    cnt %= MOD;
    33
    ans += (1LL << bit) * cnt;
    34
    ans %= MOD;
    35
    }
    36
    37
    cout << ans << "\n";
    38
    }
  4. You are given an array arrarr of length nn. What is the maximum sum of XOR values of two non-overlapping subarrays of arrarr?

    Constraints:

    • 1n1051 \leq n \leq 10^5
    • 1arr[i]1091 \leq arr[i] \leq 10^9
    Solution
    1
    class Node {
    2
    public:
    3
    Node *ch[2];
    4
    Node() { ch[0] = ch[1] = nullptr; }
    5
    };
    6
    7
    class Trie {
    8
    public:
    9
    Node *root;
    10
    11
    Trie() { root = new Node(); }
    12
    13
    void add(int x) {
    14
    Node *cur = root;
    15
    for (int i = 30; i >= 0; i--) {
    16
    int bit = (x >> i) & 1;
    17
    if (!cur->ch[bit])
    18
    cur->ch[bit] = new Node();
    19
    cur = cur->ch[bit];
    20
    }
    21
    }
    22
    23
    int getMaxXor(int v) {
    24
    Node *cur = root;
    25
    int ans = 0;
    26
    for (int i = 30; i >= 0; i--) {
    27
    int bit = (v >> i) & 1;
    28
    if (cur->ch[!bit]) {
    29
    ans += (1 << i);
    30
    cur = cur->ch[!bit];
    31
    } else
    32
    cur = cur->ch[bit];
    33
    }
    34
    35
    return ans;
    36
    }
    37
    };
    38
    39
    int main() {
    40
    int n;
    41
    cin >> n;
    42
    43
    vector<int> arr(n);
    44
    for (int i = 0; i < n; i++)
    45
    cin >> arr[i];
    46
    47
    vector<int> pref(n);
    48
    Trie t1;
    49
    t1.add(0);
    50
    int cur = 0;
    51
    for (int i = 0; i < n; i++) {
    52
    cur ^= arr[i];
    53
    pref[i] = t1.getMaxXor(cur);
    54
    t1.add(cur);
    55
    }
    56
    57
    vector<int> suff(n);
    58
    Trie t2;
    59
    t2.add(0);
    60
    cur = 0;
    61
    for (int i = n - 1; i >= 0; i--) {
    62
    cur ^= arr[i];
    63
    suff[i] = t2.getMaxXor(cur);
    64
    t2.add(cur);
    65
    }
    66
    67
    int ans = 0;
    68
    for (int i = 0; i < n - 1; i++)
    69
    ans = max(ans, pref[i] + suff[i + 1]);
    70
    cout << ans << "\n";
    71
    72
    return 0;
    73
    }

Online Assessment Questions

  1. Shilpa wants to go to a movie with her friends. There are NN friends including Svipa. MM different offers are available. A different number of tickets are sold at different group booking rates. For example, a single ticket may cost 1010 rupees, two tickets may cost 4040 rupees together. The ticket seller always introduces MM offers which are always equal to the number of friends NN. Determine how can he do it given MM and the MM costs for the tickets together, k1,k2,...,kNk_1, k_2, ..., k_N. Ticket seller would like to maximise his profit.

    Constraints:

    • 1n1031 \leq n \leq 10^3
    • m=nm = n
    • 1ki1091 \leq k_i \leq 10^9
    Solution
    1
    int main()
    2
    {
    3
    int n;
    4
    cin >> n;
    5
    6
    vector<long long> cost(n);
    7
    for (int i = 0; i < n; i++)
    8
    cin >> cost[i];
    9
    10
    vector<long long> dp(n + 1, 0);
    11
    for (int i = 1; i <= n; i++)
    12
    for (int j = 1; j <= i; j++)
    13
    dp[i] = max(dp[i], dp[i - j] + cost[j - 1]);
    14
    15
    cout << dp[n] << "\n";
    16
    }
  2. After delivering a lecture on rainwater harvesting on Environment day, the Director of the Institute asks students to construct a pit that allows rainwater harvesting in the backyard. The recharge pit is made up of N×MN \times M cells, where NN is the number of departments and MM is the number of students from each department. Each student has to raise or lower the soil level in the cell allotted to him/her to harvest rainwater. The students work as a team and decide the level of each coll considering the slope of the land, porosity, and texture of the soil. After completing the work, the final layout is represented as integers where G[i][j]G[i][j] represents the ground level at the cell (i,j)(i, j). Negative values represents dug up areas and positive values represents raised areas. Water can be trapped in a cell only if all the four sides of a cell are above the cell level. You are given the elevation map which shows the level of each cell. Write a program to find the quantity of water that can be trapped in the recharge pit.

    Constraints:

    • 1n,m1031 \leq n, m \leq 10^3
    • 103G[i][j]103-10^3 \leq G[i][j] \leq 10^3
    Solution
    1
    int trapRainWater(vector<vector<int>> &g)
    2
    {
    3
    int Y = g.size(), X = g[0].size();
    4
    5
    int ans = 0;
    6
    7
    vector<vector<int>> vis(Y, vector<int>(X, 0));
    8
    priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>>> pq;
    9
    10
    // Handle the boundary cells
    11
    for (int i = 0; i < Y; i++)
    12
    for (int j = 0; j < X; j++)
    13
    if (i == 0 || i == Y - 1 || j == 0 || j == X - 1)
    14
    {
    15
    // If dug up, then add to the answer and set them to ground level
    16
    if (g[i][j] < 0)
    17
    {
    18
    ans += -g[i][j];
    19
    g[i][j] = 0;
    20
    }
    21
    pq.push({g[i][j], i, j});
    22
    vis[i][j] = 1;
    23
    }
    24
    25
    int dx[] = {0, 0, 1, -1};
    26
    int dy[] = {1, -1, 0, 0};
    27
    28
    while (!pq.empty())
    29
    {
    30
    auto t = pq.top();
    31
    pq.pop();
    32
    33
    int h = t[0], x = t[1], y = t[2];
    34
    for (int k = 0; k < 4; k++)
    35
    {
    36
    int nx = x + dx[k], ny = y + dy[k];
    37
    if (nx >= 0 && nx < Y && ny >= 0 && ny < X && !vis[nx][ny])
    38
    {
    39
    vis[nx][ny] = 1;
    40
    // If the same is lower that current level,
    41
    // we can store the water and update the height
    42
    if (g[nx][ny] < h)
    43
    {
    44
    ans += h - g[nx][ny];
    45
    g[nx][ny] = h;
    46
    }
    47
    48
    // Always push to the pq if not visited,
    49
    // irrespective of the height
    50
    pq.push({g[nx][ny], nx, ny});
    51
    }
    52
    }
    53
    }
    54
    55
    return ans;
    56
    }
    57
    58
    int main()
    59
    {
    60
    int n, m;
    61
    cin >> n >> m;
    62
    63
    vector<vector<int>> g(n, vector<int>(m));
    64
    for (int i = 0; i < n; i++)
    65
    for (int j = 0; j < m; j++)
    66
    cin >> g[i][j];
    67
    68
    cout << trapRainWater(g) << "\n";
    69
    }

Winzo

Online Assessment Questions

  1. You are given two strings s1s_1 and s2s_2 representing the two deck of cards of length 5252 each. Two players are playing the game. The game is started by player 11. The player in his turn can choose either of the string, and take one card either from the beginning or the end of the string, and add the score associated with the same to his score. The objective of the game is to maximise the score. If both of the players play optimally, what will the difference in the score of player 11 and player 22 finally?

    • The score associated with Ace is 11, King is 1313, Queen is 1212, Jack is 1111, and the rest of the cards have the same score as their face value.
    • Ace card is represented by A, 1010 as T, King as K, Queen as Q, and Jack as J.
  2. You are given an array of length nn. For each pair of indexes (i,j)(i, j), you need to add arr[j]arr[i]arr[j] - arr[i] to the score if jij - i is positive prime number. Calculate the score for the given array.

    Constraints:

    • 1n1031 \leq n \leq 10^3
    • 1arr[i]1031 \leq arr[i] \leq 10^3
  3. You are given a matrix of size n×3n \times 3. You need to go from the first row to the last row. You cannot step into the same column for two consecutive rows. Find the maximum sum that can be obtained.

    Constraints:

    • 1n1051 \leq n \leq 10^5
    • 1arr[i][j]1091 \leq arr[i][j] \leq 10^9

Typeface

Other Campus Questions

  1. You are given an array arrarr of length nn representing the heights of the towers in a line. A tower xx is visible from the tower yy if all the towers between xx and yy have height strictly less that the height of tower xx. For each tower determine the number of towers visible from it both towards the left and the right.

    Constraints:

    • 1n1051 \leq n \leq 10^5
    • 1arr[i]1091 \leq arr[i] \leq 10^9
    Solution
    1
    int main()
    2
    {
    3
    int n;
    4
    cin >> n;
    5
    6
    vector<int> arr(n);
    7
    for (int i = 0; i < n; i++)
    8
    cin >> arr[i];
    9
    10
    vector<int> left(n);
    11
    // Maintain a monotonic decreasing stack
    12
    stack<int> st;
    13
    for (int i = 0; i < n; i++)
    14
    {
    15
    left[i] = st.size();
    16
    while (!st.empty() && arr[st.top()] <= arr[i])
    17
    st.pop();
    18
    st.push(i);
    19
    }
    20
    21
    vector<int> right(n);
    22
    while (!st.empty())
    23
    st.pop();
    24
    for (int i = n - 1; i >= 0; i--)
    25
    {
    26
    right[i] = st.size();
    27
    while (!st.empty() && arr[st.top()] <= arr[i])
    28
    st.pop();
    29
    st.push(i);
    30
    }
    31
    32
    for (int i = 0; i < n; i++)
    33
    cout << left[i] + right[i] << " ";
    34
    }
  2. Given an array of integers arrarr of length nn, determine the number of triplets (i,j,k)(i, j, k) such that i<j<ki < j < k and the product arr[i]arr[j]arr[k]arr[i] \cdot arr[j] \cdot arr[k] is even. Return the count modulo 109+710^9 + 7.

    Constraints:

    • 1n1051 \leq n \leq 10^5
    • 1arr[i]1091 \leq arr[i] \leq 10^9
    Solution
    1
    int main()
    2
    {
    3
    int n;
    4
    cin >> n;
    5
    6
    vector<int> arr(n);
    7
    for (int i = 0; i < n; i++)
    8
    cin >> arr[i];
    9
    10
    long long ans = 0, MOD = 1e9 + 7;
    11
    12
    long long cntOdd = 0;
    13
    for (int i = 0; i < n; i++)
    14
    {
    15
    if (arr[i] % 2 == 0)
    16
    {
    17
    // i is even
    18
    long long rem = n - i - 1;
    19
    ans += rem * (rem - 1) / 2;
    20
    ans %= MOD;
    21
    22
    // i is odd, j is even
    23
    ans += cntOdd * rem;
    24
    ans %= MOD;
    25
    26
    // i, j are odd, k is even
    27
    ans += cntOdd * (cntOdd - 1) / 2;
    28
    ans %= MOD;
    29
    }
    30
    else
    31
    cntOdd++;
    32
    }
    33
    34
    cout << ans << "\n";
    35
    }
  3. Given three strings, texttext, prefixStringprefixString, and suffixStringsuffixString, find:

    • prefixScoreprefixScore: The longest substring of text matching the end of prefixStringprefixString
    • suffixScoresuffixScore: The longest substring of text matching the beginning of suffixStringsuffixString

    Sum the lengths of the two strings to get the textScoretextScore. The substring of text that begins with the matching prefix and ends with matching suffix, and has the highest textScoretextScore, is the correct value to return. If there are other substrings with equal textScoretextScore, return the lexicographically lowest substring.

    Constraints:

    • 1text,prefixString,suffixString501 \leq |text|, |prefixString|, |suffixString| \leq 50
  4. There are nn points on a grid with coordinates as (xi,yi)(x_i, y_i). Whenever a point is marked, all the points within a distance of dd units in the same column and row of the marked points are also automatically marked. Note that the marking of the points is transitive and chainable. What is the minimum number of points you need to mark to finally mark all the points?

    Constraints:

    • 1n1051 \leq n \leq 10^5
    • 1d1091 \leq d \leq 10^9
    • 1xi,yi1091 \leq x_i, y_i \leq 10^9
    Solution
    1
    class DSU
    2
    {
    3
    vector<int> par, sz;
    4
    int comps;
    5
    6
    public:
    7
    DSU(int n)
    8
    {
    9
    par.resize(n);
    10
    sz.resize(n, 1);
    11
    for (int i = 0; i < n; i++)
    12
    par[i] = i;
    13
    comps = n;
    14
    }
    15
    16
    int find(int x)
    17
    {
    18
    if (par[x] == x)
    19
    return x;
    20
    return par[x] = find(par[x]);
    21
    }
    22
    23
    void unite(int a, int b)
    24
    {
    25
    a = find(a);
    26
    b = find(b);
    27
    if (a == b)
    28
    return;
    29
    if (sz[a] < sz[b])
    30
    swap(a, b);
    31
    par[b] = a;
    32
    sz[a] += sz[b];
    33
    comps--;
    34
    }
    35
    36
    int components()
    37
    {
    38
    return comps;
    39
    }
    40
    };
    41
    42
    int main()
    43
    {
    44
    int n, d;
    45
    cin >> n >> d;
    46
    47
    vector<pair<int, int>> pts(n);
    48
    map<int, vector<pair<int, int>>> mpX, mpY;
    49
    50
    for (int i = 0; i < n; i++)
    51
    {
    52
    cin >> pts[i].first >> pts[i].second;
    53
    mpX[pts[i].first].push_back({pts[i].second, i});
    54
    mpY[pts[i].second].push_back({pts[i].first, i});
    55
    }
    56
    57
    DSU dsu(n);
    58
    59
    for (auto &[_, pts] : mpX)
    60
    {
    61
    sort(pts.begin(), pts.end());
    62
    for (int i = 0; i + 1 < pts.size(); i++)
    63
    {
    64
    if (pts[i + 1].first - pts[i].first <= d)
    65
    dsu.unite(pts[i].second, pts[i + 1].second);
    66
    }
    67
    }
    68
    69
    for (auto &[_, pts] : mpY)
    70
    {
    71
    sort(pts.begin(), pts.end());
    72
    for (int i = 0; i + 1 < pts.size(); i++)
    73
    {
    74
    if (pts[i + 1].first - pts[i].first <= d)
    75
    dsu.unite(pts[i].second, pts[i + 1].second);
    76
    }
    77
    }
    78
    79
    cout << dsu.components() << "\n";
    80
    }

Online Assessment Questions

  1. You are given a directed graph of nn nodes. You are also given mm nodes in array arrarr. Return the count of the descendants of any of the given mm nodes.

    Constraints:

    • 1n1051 \leq n \leq 10^5
    • 1m1051 \leq m \leq 10^5
  2. You are given an array of umbrella sizes as arrarr of length nn. You need to get the umbrellas to so that the total size of them is exactly kk. What is the minimum number of umbrellas that you need to buy? You can buy the same sized umbrella multiple times.

    Constraints:

    • 1n1031 \leq n \leq 10^3
    • 1arr[i]1031 \leq arr[i] \leq 10^3
    • 1k1031 \leq k \leq 10^3
  3. You are given a undirected weighted tree of nn nodes. Each node is associated with a value arr[u]arr[u]. You need to determine the number of valid pairs (u,v)(u, v) in the graph. A pair (u,v)(u, v) is called valid only if uu is an ancestor of vv (not equal to vv) and the distance between uu and vv is less than or equal to arr[v]arr[v].

    Constraints:

    • 1n1051 \leq n \leq 10^5
    • 1arr[i]1091 \leq arr[i] \leq 10^9
    • 1w1091 \leq w \leq 10^9
    • 1u,vn1 \leq u, v \leq n

Media.net

Other Campus Questions

  1. You are given a tree of nn nodes. You need to find the maximum XOR of the subtree sums of two non-overlapping subtrees in the given tree. The tree is assumed to be rooted at node 11.

    Constraints:

    • 1n1051 \leq n \leq 10^5
    • 1arr[i]1041 \leq arr[i] \leq 10^4
    Solution
    1
    class Node
    2
    {
    3
    public:
    4
    Node *ch[2];
    5
    Node() { ch[0] = ch[1] = nullptr; }
    6
    };
    7
    8
    class Trie
    9
    {
    10
    public:
    11
    Node *root;
    12
    13
    Trie() { root = new Node(); }
    14
    15
    void add(int x)
    16
    {
    17
    Node *cur = root;
    18
    for (int i = 30; i >= 0; i--)
    19
    {
    20
    int bit = (x >> i) & 1;
    21
    if (!cur->ch[bit])
    22
    cur->ch[bit] = new Node();
    23
    cur = cur->ch[bit];
    24
    }
    25
    }
    26
    27
    int getMaxXor(int v)
    28
    {
    29
    Node *cur = root;
    30
    int ans = 0;
    31
    for (int i = 30; i >= 0; i--)
    32
    {
    33
    int bit = (v >> i) & 1;
    34
    if (cur->ch[!bit])
    35
    {
    36
    ans += (1 << i);
    37
    cur = cur->ch[!bit];
    38
    }
    39
    else
    40
    cur = cur->ch[bit];
    41
    }
    42
    43
    return ans;
    44
    }
    45
    };
    46
    47
    int main() {
    48
    int n;
    49
    cin >> n;
    50
    51
    vector<vector<int>> g(n);
    52
    for (int i = 0; i < n - 1; i++) {
    53
    int u, v;
    54
    cin >> u >> v;
    55
    g[u].push_back(v);
    56
    g[v].push_back(u);
    57
    }
    58
    59
    vector<int> arr(n);
    60
    for (int i = 0; i < n; i++)
    61
    cin >> arr[i];
    62
    63
    int ans = 0;
    64
    Trie t;
    65
    vector<int> sub(n);
    66
    67
    function<void(int, int)> dfs = [&](int u, int p) -> void {
    68
    // Calculate the subtree sum
    69
    sub[u] = arr[u];
    70
    for (int v : g[u]) {
    71
    if (v == p)
    72
    continue;
    73
    sub[u] += sub[v];
    74
    }
    75
    76
    // Calculate the answer and explore for the children
    77
    ans = max(ans, t.getMaxXor(sub[u]));
    78
    for (int v: g[u]) {
    79
    if (v == p)
    80
    continue;
    81
    dfs(v, u);
    82
    }
    83
    84
    t.add(sub[u]);
    85
    };
    86
    87
    dfs(0, -1);
    88
    cout << ans << "\n";
    89
    }
  2. Merge K Sorted Lists

  3. BST Iterator

    Solution
    1
    class BSTIterator
    2
    {
    3
    TreeNode *node;
    4
    stack<TreeNode *> st;
    5
    6
    public:
    7
    BSTIterator(TreeNode *root)
    8
    {
    9
    node = root;
    10
    while (node)
    11
    {
    12
    st.push(node);
    13
    node = node->left;
    14
    }
    15
    }
    16
    17
    int next()
    18
    {
    19
    node = st.top();
    20
    st.pop();
    21
    22
    int val = node->val;
    23
    node = node->right;
    24
    while (node)
    25
    {
    26
    st.push(node);
    27
    node = node->left;
    28
    }
    29
    30
    return val;
    31
    }
    32
    33
    bool hasNext()
    34
    {
    35
    return node != nullptr || !st.empty();
    36
    }
    37
    };
  4. Difference between Maximum and Minimum Price Sum

    Solution
    1
    class Solution {
    2
    void dfs(int u, int p, vector<vector<int>> &g, vector<long long> &mx, vector<long long> &smx, vector<int> &arr) {
    3
    mx[u] = arr[u], smx[u] = arr[u];
    4
    5
    for (int v: g[u]) {
    6
    if (v == p)
    7
    continue;
    8
    dfs(v, u, g, mx, smx, arr);
    9
    long long l = arr[u] + mx[v];
    10
    if (l >= mx[u]) {
    11
    smx[u] = mx[u];
    12
    mx[u] = l;
    13
    } else if (l > smx[u])
    14
    smx[u] = l;
    15
    }
    16
    }
    17
    18
    void dfs2(
    19
    int u,
    20
    int p,
    21
    vector<vector<int>> &g,
    22
    vector<long long> &mx,
    23
    vector<long long> &smx,
    24
    vector<long long> &ans,
    25
    vector<int> &arr
    26
    ) {
    27
    for (int v: g[u]) {
    28
    if (v == p)
    29
    continue;
    30
    31
    // Calculate the path with parent node
    32
    long long newPath = (mx[v] + arr[u] == mx[u] ? smx[u] : mx[u]) + arr[v];
    33
    long long org1 = mx[v], org2 = smx[v];
    34
    35
    ans[v] = max(mx[v], newPath) - arr[v];
    36
    // Update the values for the subtree of v
    37
    if (newPath >= mx[v]) {
    38
    smx[v] = mx[v];
    39
    mx[v] = newPath;
    40
    } else if (newPath > smx[v])
    41
    smx[v] = newPath;
    42
    43
    dfs2(v, u, g, mx, smx, ans, arr);
    44
    mx[v] = org1, smx[v] = org2;
    45
    }
    46
    }
    47
    48
    public:
    49
    long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& arr) {
    50
    vector<vector<int>> g(n);
    51
    for (auto e: edges) {
    52
    g[e[0]].push_back(e[1]);
    53
    g[e[1]].push_back(e[0]);
    54
    }
    55
    56
    vector<long long> mx(n), smx(n);
    57
    dfs(0, -1, g, mx, smx, arr);
    58
    vector<long long> ans(n);
    59
    ans[0] = mx[0] - arr[0];
    60
    dfs2(0, -1, g, mx, smx, ans, arr);
    61
    62
    return *max_element(ans.begin(), ans.end());
    63
    }
    64
    };
  5. You live in Orange town. There are a lot of markets around that are connected with roads. These markets sell oranges at some prices. The town is not very well developed and they still use carts to transport goods from one place to the other. The roads connect two markets together and have one attribute associated with them. The attribute is the price to go from one market to the other in an empty cart. The town also has a tax factor, the tax factor is the number by which the price associated with a road needs to be multiplied, so it can go from one market to the other IF you are carrying oranges in your cart. So if a road’s original price was 55 coins and tax factor of the town was 66 then in an empty cart it would take 55 coins to travel the road but if the cart contained oranges, it would cost 56=305 \cdot 6 = 30 coins.

    You wonder what would be the cheapest way to buy oranges if you were initially at each market. You can either buy at the market you’re at or travel to some other market, buy oranges there, and travel back to the original market.

    You are given an integer AA denoting the number of total markets in orange town, an integer array BB denoting the price of purchasing oranges at each market, a 2D2D array CC containing the information about the roads where each row contains three values. The first two values denote the market numbers that are bi-directionally connected via the road and the third value is the price. You are also given an integer DD, which is the tax factor for the orange town.

    Find and return the required array where each element is the minimum cost to buy oranges at each market such that the starting and ending point is that market.

    Constraints:

    • 1A1051 \leq A \leq 10^5
    • B=A|B| = A
    • 1B[i]1071 \leq B[i] \leq 10^7
    • 1C21051 \leq |C| \leq 2 \cdot 10^5
    • 1C[i][0],C[i][1]A1 \leq C[i][0], C[i][1] \leq A
    • 1C[i][2]1031 \leq C[i][2] \leq 10^3
    • 1D51 \leq D \leq 5
    Solution

    The key to solving this problem is to realize that we are following a path from uu to vv to buy oranges, then you will follow the path in the reverse order from vv to uu (and both of the paths will have the shortest cost). This enables us to use the cost of an edge as w(tax+1)w \cdot (tax + 1) where ww is the original cost of the edge and taxtax is the tax factor of the town. Now we can use a multi-source Dijkstra algorithm to find the shortest path from all the markets to all the other markets.

    1
    int main() {
    2
    int n;
    3
    cin >> n;
    4
    5
    vector<long long> cost(n);
    6
    for (int i = 0; i < n; i++)
    7
    cin >> cost[i];
    8
    9
    vector<vector<pair<int, long long>>> g(n);
    10
    int m;
    11
    cin >> m;
    12
    for (int i = 0; i < m; i++) {
    13
    int u, v, w;
    14
    cin >> u >> v >> w;
    15
    u--, v--;
    16
    g[u].push_back({v, w});
    17
    g[v].push_back({u, w});
    18
    }
    19
    20
    long long tax;
    21
    cin >> tax;
    22
    23
    vector<long long> dis(n, LLONG_MAX);
    24
    priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;
    25
    26
    for (int i = 0; i < n; i++) {
    27
    dis[i] = cost[i];
    28
    pq.push({dis[i], i});
    29
    }
    30
    31
    while (!pq.empty()) {
    32
    auto [d, u] = pq.top();
    33
    pq.pop();
    34
    35
    if (dis[u] != d)
    36
    continue;
    37
    38
    for (auto [v, w]: g[u]) {
    39
    long long newCost = d + w * (tax + 1);
    40
    if (newCost < dis[v]) {
    41
    dis[v] = newCost;
    42
    pq.push({dis[v], v});
    43
    }
    44
    }
    45
    }
    46
    47
    for (int i = 0; i < n; i++)
    48
    cout << dis[i] << " ";
    49
    }
  6. You are given an array AA. You need to create an array BB, which is a subsequence of AA and satisfies both the following conditions:

    • B[i]<B[i+1]B[i] < B[i + 1] where 1iB1 \leq i \leq |B|
    • cnt(B[1]B[2]....B[i])cnt(B[i+1])cnt(B[1] \oplus B[2] .... \oplus B[i]) \leq cnt(B[i + 1]) where 1i<B1 \leq i < |B|, cnt(t)cnt(t) is the number of set bits present in the binary representation of tt and \oplus is the bitwise XOR operator.

    Let XX be the bitwise XOR of all the elements in valid array BB. You need to find the number of different values of XX that can be formed.

    Constraints:

    • 1A1051 \leq |A| \leq 10^5
    • 1A[i]1001 \leq A[i] \leq 100
    Solution
    1
    int main() {
    2
    int n;
    3
    cin >> n;
    4
    5
    vector<int> arr(n);
    6
    for (int i = 0; i < n; i++)
    7
    cin >> arr[i];
    8
    9
    vector<int> cnt(128, 0);
    10
    for (int i = 0; i < n; i++)
    11
    cnt[i] = __builtin_popcount(arr[i]);
    12
    13
    // Smallest last value for subsequence till idx and having XOR as j
    14
    vector<vector<int>> dp(n, vector<int> (128, 1e9));
    15
    dp[0][arr[0]] = arr[0];
    16
    17
    for (int idx = 0; idx < n - 1; idx++)
    18
    for (int j = 0; j < 128; j++) {
    19
    dp[idx + 1][j] = min(dp[idx + 1][j], dp[idx][j]);
    20
    if (arr[idx + 1] > dp[idx][j] && cnt[arr[idx + 1]] >= cnt[j]) {
    21
    int newXor = j ^ arr[idx + 1];
    22
    dp[idx + 1][newXor] = min(dp[idx + 1][newXor], arr[idx + 1]);
    23
    }
    24
    }
    25
    26
    int ans = 0;
    27
    for (int i = 0; i < 128; i++)
    28
    if (dp[n - 1][i] != 1e9)
    29
    ans++;
    30
    cout << ans << "\n";
    31
    }
  7. Carl is bored of playing with ordinary prime numbers. Thus, he comes up with some special numbers called Omega Primes. A number XX is called an omega Prime, if there exists no perfect square YY such that Y>1Y > 1 and such that YY divides XX. For example, 66 is an Omega Prime because there is no perfect square except 11 that divides 66. On the other hand, 1212 is not an Omega Prime as 44 (which is a perfect square) is a divisor of 1212.

    Carl decides to play a bit more with Omega Primes. He has an array AA of integers. Carl wants to find the number of different subsets such that the product of elements for each subset, results in an Omega Prime. Help Carl find this number. Since this number can be large, output the answer modulo 109+710^9 + 7.

    Constraints:

    • 1A1051 \leq |A| \leq 10^5
    • 1A[i]301 \leq A[i] \leq 30

    This is a restatement of the question Count Number of Good Subsets on LeetCode.

  8. Bitmasks are cool. A bitmask is a string of binary bits (00 and 11). For example: 01010 is a bitmask. Kuldeep is a naughty but brilliant computer scientist. In his free time, he writes some random programs to play with bitmasks. He has a PhD student under him and to test him (and entertain himself), he has given him the following task:

    Given a number NN, write a bitmask of length NN containing all 00. Now, you are given QQ operations. Each operation contains two numbers (l,r)(l, r) as input. An operation can be one of the following:

    • Update operation: Take the XOR of all the bits in the bitmask from index ll to rr (both inclusive) with 11.
    • Query operation: Count the number of set bits in the bitmask between index ll to rr (both inclusive).

    You need to find the sum of all the queries.

    Constraints:

    • 1N1051 \leq N \leq 10^5
    • 1Q1051 \leq Q \leq 10^5
    • 1l,rN1 \leq l, r \leq N
  9. Flatten a Binary Tree to a Linked List

  10. Scramble String

  11. You are given a graph GG of NN nodes and MM edges and each edge has some time associated with it. There is a policeman standing on each node except Node NN. All of them get a report that there is thief on Node NN and the policemen start moving towards it, but all of them have been hungry for days, so they are looking to visit a few restaurants as well, before reaching the node NN. There are KK restaurants present on some nodes, and each restaurant has some satisfaction. Now, a policeman will only go to a restaurant if and only if the satisfaction he receives by reaching the restaurant is greater than or equal to the time he has invested in reaching there and then going to the Node NN. Find and return the number of policemen who will have a meal at a restaurant.

    Constraints:

    • 1N,M,K1051 \leq N, M, K \leq 10^5
    Solution
    1
    int main()
    2
    {
    3
    int n, m;
    4
    cin >> n >> m;
    5
    6
    vector<vector<pair<int, int>>> g(n);
    7
    for (int i = 0; i < m; i++)
    8
    {
    9
    int u, v, w;
    10
    cin >> u >> v >> w;
    11
    g[u - 1].push_back({v - 1, w});
    12
    g[v - 1].push_back({u - 1, w});
    13
    }
    14
    15
    int k;
    16
    cin >> k;
    17
    vector<pair<int, int>> res(k);
    18
    for (int i = 0; i < k; i++)
    19
    {
    20
    cin >> res[i].first >> res[i].second;
    21
    res[i].first--;
    22
    }
    23
    24
    // Distance of all the nodes from the node n - 1
    25
    vector<long long> dis(n, 1e18);
    26
    priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;
    27
    dis[0] = 0;
    28
    pq.push({0, 0});
    29
    while (!pq.empty())
    30
    {
    31
    auto [d, u] = pq.top();
    32
    pq.pop();
    33
    34
    if (d != dis[u])
    35
    continue;
    36
    37
    for (auto [v, w] : g[u])
    38
    if (dis[v] > dis[u] + w)
    39
    {
    40
    dis[v] = dis[u] + w;
    41
    pq.push({dis[v], v});
    42
    }
    43
    }
    44
    45
    // The maximum value of satisfaction - distance travelled for all the nodes
    46
    priority_queue<pair<long long, int>> pq2;
    47
    vector<long long> dis2(n, -1e18);
    48
    for (auto [v, s] : res)
    49
    {
    50
    dis2[v] = s - dis[v];
    51
    pq2.push({dis2[v], v});
    52
    }
    53
    54
    while (!pq2.empty())
    55
    {
    56
    auto [d, u] = pq2.top();
    57
    pq2.pop();
    58
    59
    if (d != dis2[u])
    60
    continue;
    61
    62
    for (auto [v, w] : g[u])
    63
    if (dis2[v] < dis2[u] - w)
    64
    {
    65
    dis2[v] = dis2[u] - w;
    66
    pq2.push({dis2[v], v});
    67
    }
    68
    }
    69
    70
    int cnt = 0;
    71
    for (int i = 0; i < n - 1; i++)
    72
    if (dis2[i] >= 0)
    73
    cnt++;
    74
    75
    cout << cnt << "\n";
    76
    }
  12. Fill the Bag

    Solution
    1
    void solution()
    2
    {
    3
    ll n, w;
    4
    cin >> w;
    5
    cin >> n;
    6
    7
    vll arr(n);
    8
    vll have(64, 0);
    9
    10
    range(i, 0, n) cin >> arr[i];
    11
    range(i, 0, n) range(j, 0, 64) if ((1ll << j) & arr[i]) have[j]++;
    12
    13
    int ans = 0;
    14
    15
    range(i, 0, 64)
    16
    {
    17
    bool req = (1LL << i) & w;
    18
    19
    if (have[i] >= req)
    20
    {
    21
    have[i] -= req;
    22
    if (i + 1 < 64)
    23
    have[i + 1] += have[i] / 2;
    24
    continue;
    25
    }
    26
    27
    if (!req)
    28
    continue;
    29
    30
    bool found = false;
    31
    for (int j = i + 1; j < 64; j++)
    32
    if (have[j])
    33
    {
    34
    found = true;
    35
    ans += j - i;
    36
    have[j] -= 1;
    37
    have[i] = 2;
    38
    range(k, i + 1, j) have[k] = 1;
    39
    i--;
    40
    break;
    41
    }
    42
    if (!found)
    43
    {
    44
    cout << -1 << "\n";
    45
    return;
    46
    }
    47
    }
    48
    49
    cout << ans << "\n";
    50
    }
  13. Given a complete rooted tree with NN nodes numbered 11 to NN. This tree has it’s leaves at the top and root at the bottom. A complete tree is a tree on every leaf of the tree and in order to get all the fruits you have to shake the tree any number of times. But this tree is a little different than the rest it has following properties:

    • Every node has its capacity value that represents the number of fruits a node can hold at any moment.
    • Only one fruit falls from each node to its present node in one shake.
    • If a number of fruits at a node is more than its capacity then excess fruits (greater than capacity) on that node at that instant will fall to the ground. This process happens instantaneously hence no shake is required.
    • The tree is rooted at 1.
    • You may assume that root is one level above the ground so all fruits which fall from roots lands on the ground.

    You have to find the minimum number of shakes you have to perform such that all the fruits are on the ground.

    Constraints:

    • 1N1051 \leq N \leq 10^5
    • 1A[i],B[i]<=1091 \leq A[i], B[i] <= 10^9
    • 1C[i][0],C[i][1]N1 \leq C[i][0], C[i][1] \leq N
    • A[i]=0A[i] = 0 for non-leaf nodes
    • Initially A[i]B[i]A[i] \leq B[i]
    Solution
    1
    int main() {
    2
    int n;
    3
    cin >> n;
    4
    5
    vector<int> arr(n);
    6
    for (int i = 0; i < n; i++)
    7
    cin >> arr[i];
    8
    vector<int> cap(n);
    9
    for (int i = 0; i < n; i++)
    10
    cin >> cap[i];
    11
    12
    vector<vector<int>> g(n);
    13
    for (int i = 0; i < n - 1; i++) {
    14
    int u, v;
    15
    cin >> u >> v;
    16
    u--, v--;
    17
    g[u].push_back(v);
    18
    g[v].push_back(u);
    19
    }
    20
    21
    // ans -> Min time to empty the node
    22
    // sum -> Total fruits falling from child
    23
    // depth -> Depth of the node with respect to the leaves
    24
    vector<int> ans(n), sum(n), depth(n);
    25
    26
    function<void(int, int)> dfs = [&](int u, int p) -> void {
    27
    // Leaf node
    28
    if (g[u].size() == 1 && u != 0) {
    29
    ans[u] = arr[u];
    30
    depth[u] = 0;
    31
    sum[u] = 0;
    32
    return;
    33
    }
    34
    35
    int maxChild = 0;
    36
    sum[u] = 0;
    37
    38
    for (int v: g[u]) {
    39
    if (v == p)
    40
    continue;
    41
    dfs(v, u);
    42
    sum[u] += ans[v] - depth[v];
    43
    depth[u] = max(depth[u], depth[v] + 1);
    44
    maxChild = max(maxChild, ans[v]);
    45
    }
    46
    47
    ans[u] = maxChild + min(cap[u], sum[u] - (maxChild - depth[u]));
    48
    };
    49
    dfs(0, -1);
    50
    51
    cout << ans[0] << "\n";
    52
    }
  14. You are the prime minister of a country and once you went for a world tour. After 55 years, when you returned to your country you were shocked to see the condition of the roads between the cities. So, you plan to repair them, but you cannot afford to spend a lot of money. The country can be represented as a N×MN \times M grid, where country[i,j]country[i,j] is a city The cost of repairing a repairing a road between [i,j][i,j] and [i+1,j][i+1,j] is A[i]A[i] and the cost of repairing a road between [i,j][i,j] and [i,j+1][i,j+1] is B[i]B[i]. Return the minimum cost of repairing roads such that all cities become a connected network. As the cost can be large, return the cost modulo 109+710^9 + 7.

    Constraints:

    • 1N,M1051 \leq N, M \leq 10^5
    • 1A[i],B[i]1091 \leq A[i], B[i] \leq 10^9
    Solution
    1
    int main()
    2
    {
    3
    long long n, m;
    4
    cin >> n >> m;
    5
    6
    vector<long long> a(n - 1), b(m - 1);
    7
    for (int i = 0; i < n - 1; i++)
    8
    cin >> a[i];
    9
    for (int i = 0; i < m - 1; i++)
    10
    cin >> b[i];
    11
    12
    sort(a.begin(), a.end());
    13
    sort(b.begin(), b.end());
    14
    15
    long long i = 0, j = 0;
    16
    long long ans = 0;
    17
    long long MOD = 1e9 + 7;
    18
    19
    while (i < n - 1 && j < m - 1)
    20
    {
    21
    if (a[i] < b[j])
    22
    {
    23
    ans += a[i] * (m - j);
    24
    i++;
    25
    }
    26
    else
    27
    {
    28
    ans += b[j] * (n - i);
    29
    j++;
    30
    }
    31
    ans %= MOD;
    32
    }
    33
    34
    while (i < n - 1)
    35
    {
    36
    ans += a[i];
    37
    i++;
    38
    }
    39
    while (j < m - 1)
    40
    {
    41
    ans += b[j];
    42
    j++;
    43
    }
    44
    ans %= MOD;
    45
    46
    cout << ans << "\n";
    47
    }

Online Assessment Questions

  1. Recover Binary Search Tree

  2. You are given an array of integers. The cost of merging two adjacent integers aa and bb is a+ba + b. After the merging, they become a single integer with the value a+ba + b. You need to find the minimum cost to merge all the integers into a single integer.

    Constraints:

    • 1A1001 \leq |A| \leq 100
    • 1A[i]1051 \leq A[i] \leq 10^5
  3. You are given an array arrarr. In one operation, you can choose any index ii, and then update all the indexes jj in the array as A[j]=A[i]A[j]A[j] = A[i] | A[j] where | is the bitwise OR operator. You need to find the minimum number of operations required to make all the elements of the array equal.

    Constraints:

    • 1A1051 \leq |A| \leq 10^5
    • 1A[i]50001 \leq A[i] \leq 5000
  4. You are given an array of strings wordswords and a target string ww. In one operation you can choose any string from wordswords and take a non empty prefix of the same. Finally at the end, you need to concatenate all the chosen prefixes such that they form the word ww. You need to find the minimum number of operations required to form the word ww. You can choose the same string multiple times.

    Constraints:

    • 1words2001 \leq |words| \leq 200
    • 1w2001 \leq |w| \leq 200
    • 1words[i]1001 \leq |words[i]| \leq 100

Samsung Research Institute Bangalore (SRIB)

SRIB is known to frequently repeat it’s questions, and the most of them are from the this very helpful repository.

Other Campus Questions

  1. You are given NN segments. Each segment has threw characteristic properties:

    • ll: The starting point of the segment
    • rr: The ending point of the segment
    • cc: The cost of the segment

    Two segments can form a valid pair, if and only if those two segments do not overlap. Segments are called overlapping if there is at least one point lying in both the segments. The cost of the pairing of two valid segments is defined as the product of their individual costs. Out of all possible valid pairs, find the valid pair of segments, for which their cost of pairing is minimal. Print that min cost of pairing.

    Constraints:

    • 1N1051 \leq N \leq 10^5
    • 1l,r,c1091 \leq l, r, c \leq 10^9
    Solution
    1
    int main()
    2
    {
    3
    int n;
    4
    cin >> n;
    5
    6
    vector<vector<long long>> arr(n, vector<long long>(3));
    7
    for (int i = 0; i < n; i++)
    8
    for (int j = 0; j < 3; j++)
    9
    cin >> arr[i][j];
    10
    11
    sort(arr.begin(), arr.end());
    12
    vector<long long> sufMin(n);
    13
    sufMin[n - 1] = arr[n - 1][2];
    14
    for (int i = n - 2; i >= 0; i--)
    15
    sufMin[i] = min(sufMin[i + 1], arr[i][2]);
    16
    17
    auto forwardSearch = [&](int idx) -> int
    18
    {
    19
    int l = idx + 1, r = n - 1;
    20
    int ans = -1;
    21
    while (l <= r)
    22
    {
    23
    int m = (l + r) / 2;
    24
    if (arr[m][0] <= arr[idx][1])
    25
    l = m + 1;
    26
    else
    27
    {
    28
    ans = m;
    29
    r = m - 1;
    30
    }
    31
    }
    32
    33
    return ans;
    34
    };
    35
    36
    long long ans = 1e18 + 10;
    37
    for (int i = 0; i < n; i++)
    38
    {
    39
    int nxt = forwardSearch(i);
    40
    if (nxt != -1)
    41
    ans = min(ans, arr[i][2] * sufMin[nxt]);
    42
    }
    43
    44
    if (ans > 1e18)
    45
    ans = -1;
    46
    cout << ans << "\n";
    47
    return 0;
    48
    }
  2. There is a knot in the middle of a necklace with NN beads at the left and the right. The red and blue beads are randomly strung into it. You want to make the number of red and blue beads equal by removing some of them. As there is a knot in the middle, you cannot remove the beads passing the knot. You can remove them only from each end of the necklace. You are required to print the minimum number of beads you should remove to make the number of the remaining red and blue beads the same. Although removing all the beads from the necklace will always mate the number of both colors equal as zero, there is a way to remove a smaller number of beads. The information of the necklace is given as string AA whose length is 2N2 \cdot N. The colors of the beads are given in order from the left and to the right end. The red bead is expressed as R, whereas the blue bead is expressed as B.

    Constraints:

    • 1N1051 \leq N \leq 10^5
    Solution
    1
    int main()
    2
    {
    3
    string s;
    4
    cin >> s;
    5
    int n = s.size();
    6
    7
    map<int, int> cnt;
    8
    int r = 0, b = 0;
    9
    cnt[0] = 0;
    10
    for (int i = n / 2; i < n; i++)
    11
    {
    12
    r += s[i] == 'R';
    13
    b += s[i] == 'B';
    14
    cnt[r - b] = i - (n / 2) + 1;
    15
    }
    16
    17
    int ans = 0;
    18
    r = 0, b = 0;
    19
    for (int i = n / 2 - 1; i >= 0; i--)
    20
    {
    21
    r += s[i] == 'R';
    22
    b += s[i] == 'B';
    23
    int d = b - r;
    24
    if (cnt.find(d) != cnt.end())
    25
    ans = max(ans, cnt[d] + n / 2 - i);
    26
    }
    27
    28
    cout << n - ans;
    29
    return 0;
    30
    }
  3. Count the number of positive integers less than or less to AA such that the sum of their digits is SS. Return the number of numbers modulo 109+710^9 + 7.

    Constraints:

    • 1A101001 \leq A \leq 10^{100}
    • 0S10000 \leq S \leq 1000
    Solution
    1
    int main()
    2
    {
    3
    string s;
    4
    cin >> s;
    5
    int n = s.size();
    6
    7
    int sum;
    8
    cin >> sum;
    9
    if (sum == 0)
    10
    {
    11
    cout << 0;
    12
    return 0;
    13
    }
    14
    15
    vector<vector<vector<long long>>> dp(n, vector<vector<long long>>(2, vector<long long>(sum + 1, -1)));
    16
    long long MOD = 1e9 + 7;
    17
    18
    function<long long(int, bool, int)> solve = [&](int idx, bool eq, int curSum) -> long long
    19
    {
    20
    if (idx == n)
    21
    return curSum == sum;
    22
    if (dp[idx][eq][curSum] != -1)
    23
    return dp[idx][eq][curSum];
    24
    25
    long long tot = 0;
    26
    int maxD = eq ? s[idx] - '0' : 9;
    27
    for (int d = 0; d <= maxD; d++)
    28
    {
    29
    bool newEq = eq & (d == maxD);
    30
    int newSum = curSum + d;
    31
    if (newSum <= sum)
    32
    {
    33
    tot += solve(idx + 1, newEq, newSum);
    34
    tot %= MOD;
    35
    }
    36
    }
    37
    38
    return dp[idx][eq][curSum] = tot;
    39
    };
    40
    41
    cout << solve(0, 1, 0);
    42
    return 0;
    43
    }
  4. There are nn balloons and nn bullets and each balloon is assigned with a particular number (point). Whenever a particular balloon is shot, the number of points increases by

    • The multiplication of points assigned to balloon on left and that of right side.
    • Points assigned to left if no right exists.
    • Points assigned to right if no left exists.
    • Points assigned to itself if no other balloon exists.

    You have to output the maximum number of points possible you can get by shooting the balloons.

    Constraints:

    • 1n1021 \leq n \leq 10^2
    Solution
    1
    int main() {
    2
    int n;
    3
    cin >> n;
    4
    5
    vector<int> arr(n);
    6
    for (int i = 0; i < n; i++)
    7
    cin >> arr[i];
    8
    9
    vector<vector<int>> dp(n, vector<int>(n, -1));
    10
    function<int(int, int)> get = [&](int l, int r) -> int {
    11
    if (l > r)
    12
    return 0;
    13
    if (dp[l][r] != -1)
    14
    return dp[l][r];
    15
    16
    int ans = 0;
    17
    for (int k = l; k <= r; k++) {
    18
    int sc;
    19
    if (k > l && k < r)
    20
    sc = arr[k - 1] * arr[k + 1];
    21
    else if (k > l)
    22
    sc = arr[k - 1];
    23
    else if (k < r)
    24
    sc = arr[k + 1];
    25
    else
    26
    sc = arr[k];
    27
    28
    ans = max(ans, sc + get(l, k - 1) + get(k + 1, r));
    29
    }
    30
    31
    return dp[l][r] = ans;
    32
    };
    33
    34
    cout << get(0, n - 1);
    35
    }
  5. Burst Ballons

  6. A doctor travels from a division to other division where divisions are connected like a graph (directed graph) and the edge weights are the probabilities of the doctor going from that division to other connected division. The doctor stays 1010 minutes at each division. You will be given a time and you have to find the division which will have the maximum probability of having him.

    • If he reaches a point where there are no further nodes then he leaves the lab after 1010 mins and goes home.
    • The traveling time is not considered, and thus at the end of the 10th10^{th} min, he will be in next division.

    Constraints:

    • Number of divisions NN (1N12)(1 \leq N \leq 12)
    • Number of test cases TT (1T10)(1 \leq T \leq 10)
    Solution
    1
    void get()
    2
    {
    3
    int n, m, t;
    4
    cin >> n >> m >> t;
    5
    int k = t / 10;
    6
    7
    vector<vector<pair<int, double>>> g(n);
    8
    for (int i = 0; i < m; i++)
    9
    {
    10
    int u, v;
    11
    double p;
    12
    cin >> u >> v >> p;
    13
    u--, v--;
    14
    g[u].push_back({v, p});
    15
    }
    16
    17
    vector<double> prob(n);
    18
    prob[0] = 1;
    19
    20
    while (k--)
    21
    {
    22
    vector<double> newProb(n, 0);
    23
    for (int i = 0; i < n; i++)
    24
    for (auto [v, p] : g[i])
    25
    newProb[v] += p * prob[i];
    26
    prob = newProb;
    27
    }
    28
    29
    double mxProb = 0;
    30
    int mxDiv = -1;
    31
    32
    for (int i = 0; i < n; i++)
    33
    {
    34
    if (prob[i] - mxProb >= 1e-6)
    35
    {
    36
    mxProb = prob[i];
    37
    mxDiv = i;
    38
    }
    39
    }
    40
    41
    mxDiv++;
    42
    if (mxDiv == 0)
    43
    cout << 0 << "\n";
    44
    else
    45
    cout << mxDiv << " " << fixed << setprecision(6) << mxProb << "\n";
    46
    }
    47
    48
    int main()
    49
    {
    50
    int t;
    51
    cin >> t;
    52
    for (int i = 0; i < t; i++)
    53
    {
    54
    cout << "#" << i + 1 << " ";
    55
    get();
    56
    }
    57
    }
  7. There are NN pots. Every pot has some water in it. They may be partially filled, so there is an overflow number OO associated with every pot which tell how many minimum stone pieces are require for that pot to overflow. So if for a pot OO value is 55, it means minimum 55 stone pieces should be put in that pot to make it overflow.

    Initially a crow watched those pots and by seeing the water level he anticipated OO value correctly for every pot (that is he knew O1O_1 to OnO_n). But when he came back in evening he found that every pot is painted from outside and he is not able to know which pot has what OO value. The crow wants some KK pots to overflow so that he can serve his child appropriately. For overflowing the pots, he needs to search for the stones in forest (assume that every stone has same size).

    He wants to use minimum number of stones to overflow the KK pots. But he doesn’t know now which pot has what OO value. So the task is to find out the minimum number of stones that the crow requires to make the KK pots overflow in the worst case.

    Constraints:

    • 1N1001 \leq N \leq 100
    • 1KN1 \leq K \leq N
    Solution
    1
    int main()
    2
    {
    3
    int n, k;
    4
    cin >> n >> k;
    5
    6
    vector<int> arr(n);
    7
    for (int i = 0; i < n; i++)
    8
    cin >> arr[i];
    9
    sort(arr.begin(), arr.end());
    10
    11
    vector<vector<int>> dp(n, vector<int>(k + 1, 1e9));
    12
    for (int i = 0; i < n; i++)
    13
    {
    14
    dp[i][0] = 0;
    15
    dp[i][1] = arr[i] * (n - i);
    16
    }
    17
    18
    function<int(int, int)> get = [&](int idx, int p) -> int
    19
    {
    20
    if (dp[idx][p] != 1e9)
    21
    return dp[idx][p];
    22
    23
    for (int last = idx + 1; last < n; last++)
    24
    {
    25
    int newCost = get(last, p - 1) + (last - idx) * arr[idx];
    26
    dp[idx][p] = min(dp[idx][p], newCost);
    27
    }
    28
    29
    return dp[idx][p];
    30
    };
    31
    32
    int ans = 1e9;
    33
    for (int i = 0; i < n; i++)
    34
    ans = min(ans, get(i, k));
    35
    cout << ans << "\n";
    36
    }
  8. Tallest Billboard

    Solution
    1
    class Solution {
    2
    public:
    3
    int tallestBillboard(vector<int>& arr) {
    4
    map<int, int> dp;
    5
    dp[0] = 0;
    6
    7
    for (int i = 0; i < arr.size(); i++) {
    8
    map<int, int> newDp = dp;
    9
    10
    for (auto [diff, taller]: dp) {
    11
    int shorter = taller - diff;
    12
    13
    // Add to taller side
    14
    int newDiff = diff + arr[i];
    15
    newDp[newDiff] = max(newDp[newDiff], taller + arr[i]);
    16
    17
    // Add to smaller side
    18
    newDiff = abs(taller - arr[i] - shorter);
    19
    newDp[newDiff] = max({
    20
    newDp[newDiff],
    21
    taller,
    22
    shorter + arr[i]
    23
    });
    24
    }
    25
    26
    dp = newDp;
    27
    }
    28
    29
    return dp[0];
    30
    }
    31
    };

Online Assessment Question

  1. You are given a grid of Y×XY \times X of 11 and 00 elements. You need to perform KK operations on the same. In one operation, you need to choose one column of the grid, and flip the values of all the cells of that column. Calculate the maximum possible number of rows that can have all the elements as 11 after performing KK operations. There are TT test cases in one test file.

    Constraints:

    • 1T101 \leq T \leq 10
    • 1Y1031 \leq Y \leq 10^3
    • 1X201 \leq X \leq 20
    • 1K201 \leq K \leq 20
    • 0grid[i][j]10 \leq grid[i][j] \leq 1
    Solution
    1
    int get()
    2
    {
    3
    int Y, X, k;
    4
    cin >> Y >> X >> k;
    5
    6
    map<int, int> cnt;
    7
    for (int i = 0; i < Y; i++)
    8
    {
    9
    int m = 0;
    10
    for (int j = 0; j < X; j++)
    11
    {
    12
    int x;
    13
    cin >> x;
    14
    m = (m << 1) | x;
    15
    }
    16
    cnt[m]++;
    17
    }
    18
    19
    int ans = 0;
    20
    int req = (1 << X) - 1;
    21
    22
    for (int mask = 0; mask < (1 << X); mask++)
    23
    {
    24
    int c = __builtin_popcount(mask);
    25
    if (k % 2 != c % 2 || c > k)
    26
    continue;
    27
    ans = max(ans, cnt[req ^ mask]);
    28
    }
    29
    30
    return ans;
    31
    }
    32
    33
    int main()
    34
    {
    35
    int t;
    36
    cin >> t;
    37
    for (int i = 0; i < t; i++)
    38
    cout << "#" << i + 1 << " " << get() << "\n";
    39
    }