0% found this document useful (0 votes)
124 views24 pages

Meesho Questions

The document contains a list of coding questions and solutions related to data structures and algorithms, including topics like segment trees, Fenwick trees, and graph traversal. Each question is accompanied by a code snippet that provides a solution in either C++ or Python. The questions cover various computational problems such as maximum profit calculations, node queries, and energy node traversal.

Uploaded by

kyamalumm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
124 views24 pages

Meesho Questions

The document contains a list of coding questions and solutions related to data structures and algorithms, including topics like segment trees, Fenwick trees, and graph traversal. Each question is accompanied by a code snippet that provides a solution in either C++ or Python. The questions cover various computational problems such as maximum profit calculations, node queries, and energy node traversal.

Uploaded by

kyamalumm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Meesho Questions :-

- Best Subsequence
- Array And Queries
- Node Queries
- Energy Nodes
- Shopping Mall
- Budget Planning
- Divisor Queries
- Max Profit
- Ben and His Work
- Two Groups
- Chain Square
- Maximum Profit
- TreeNode
- Special Sequence
- Task
- Functions Description
- Special Nodes
- XOR On ARRAY

THESE CODES ARE LEGIT WORKING CONDTIONS ​


AND ABOVE ALL QUESTIONS ARE ASKED SO I PASTED.

1- Divisor Queries ➖
#include <bits/stdc++.h>
using namespace std;

#define int long long


#define ll long long
#define endl "\n"
#define MOD 1000000007
#define MOD2 998244353
#define vll vector<ll>

struct SegmentTree {
ll N;
vll tree;
ll neutral = 0;

ll combine(ll a, ll b) {
return a + b;
}

void build(ll u, ll L, ll R, vll &v) {


if (L == R) {
tree[u] = v[L];
} else {
ll M = (L + R) / 2;
build(u * 2, L, M, v);
build(u * 2 + 1, M + 1, R, v);
tree[u] = combine(tree[u * 2], tree[u * 2 + 1]);
}
}

SegmentTree(vll v) {
N = v.size() - 1;
tree.assign(4 * N + 1, 0);
build(1, 1, N, v);
}

ll query(ll lq, ll rq, ll u, ll L, ll R) {


if (L > rq || R < lq) {
return neutral;
} else if (L >= lq && R <= rq) {
return tree[u];
} else {
ll M = (L + R) / 2;
return combine(query(lq, rq, u * 2, L, M), query(lq, rq, u * 2 + 1,
M + 1, R));
}
}

void update(ll idx, ll val, ll u, ll L, ll R) {


if (L > idx || R < idx) {
return;
} else if (L == R) {
tree[u] = val;
return;
} else {
ll M = (L + R) / 2;
update(idx, val, u * 2, L, M);
update(idx, val, u * 2 + 1, M + 1, R);
tree[u] = combine(tree[u * 2], tree[u * 2 + 1]);
}
}
};

const int MAXN = 1e6 + 1;


vector<int> spf(MAXN);

void sieve() {
spf[1] = 1;
for (int i = 2; i < MAXN; i++)
spf[i] = i;
for (int i = 4; i < MAXN; i += 2)
spf[i] = 2;
for (int i = 3; i * i < MAXN; i++) {
if (spf[i] == i) {
for (int j = i * i; j < MAXN; j += i)
if (spf[j] == j)
spf[j] = i;
}
}
}

int32_t main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);

sieve();
int n, q;
cin >> n >> q;
vll arr(n + 1);
for (int i = 1; i <= n; i++)
cin >> arr[i];

SegmentTree sgt(arr);
set<int> s;
for (int i = 1; i <= n; i++)
s.insert(i);

while (q--) {
int type;
cin >> type;
int a, b;
cin >> a >> b;

if (type == 3) {
sgt.update(a, b, 1, 1, n);
int temp = a;
auto it = s.lower_bound(temp);
if (it != s.end() && s.size() != 0 && *it == a) {
s.erase(temp);
s.insert(a);
} else {
s.insert(a);
}
arr[a] = b;
} else if (type == 2) {
cout << sgt.query(a, b, 1, 1, n) << endl;
} else {
while (a <= b) {
int temp = a;
auto it = s.lower_bound(temp);
if (it == s.end())
break;
if (*it > b)
break;
int c = *it + 1;
sgt.update(a, arr[a] / spf[arr[a]], 1, 1, n);
if (spf[a] == 1) {
s.erase(temp);
}
arr[a] = spf[a];
a = c;
}
}
}
return 0;
}

2 - NODE QUERIES ➖
def solve(edges, values, queries):
import sys
sys.setrecursionlimit(10**6)
N = len(values)
vals = [0] + values
g = [[] for _ in range(N + 1)]
for u, v in edges:
g[u].append(v)
g[v].append(u)
tin = [0] * (N + 1)
tout = [0] * (N + 1)
timer = 0
def dfs(u, p):
nonlocal timer
timer += 1
tin[u] = timer
for v in g[u]:
if v == p:
continue
dfs(v, u)
tout[u] = timer
dfs(1, -1)
diff = [0] * (N + 2)
for typ, x, y in queries:
if typ == 1:
diff[tin[x]] += y
diff[tout[x] + 1] -= y
elif typ == 2:
diff[1] += y
diff[N + 1] -= y
diff[tin[x]] -= y
diff[tout[x] + 1] += y
for i in range(1, N + 2):
diff[i] += diff[i - 1]
res = [vals[i] + diff[tin[i]] for i in range(1, N + 1)]
return res

if _name_ == '_main_':
N = int(input())
edges = []
for _ in range(N - 1):
edges.append(list(map(int, input().split())))
values = list(map(int, input().split()))
Q = int(input())
queries = []
for _ in range(Q):
queries.append(list(map(int, input().split())))
out = solve(edges, values, queries)
print(' '.join(map(str, out)))

3- Maximum Profit ➖
def max_profit(N, S, Q):
max_profit = 0

for L in range(1, N + 1):


xor_value = 0

for i in range(L):
xor_value = (xor_value << 1) | (int(S[i]) ^ int(Q[i]))

profit = (L // 2) * xor_value
max_profit = max(max_profit, profit)

for i in range(L, N):


xor_value = xor_value & ((1 << (L - 1)) - 1)
xor_value = (xor_value << 1) | (int(S[i]) ^ int(Q[i]))
profit = (L // 2) * xor_value
max_profit = max(max_profit, profit)
return max_profit

T = int(input().strip())
for _ in range(T):
N = int(input().strip())
S = input().strip()
Q = input().strip()
print(max_profit(N, S, Q))

4- Ben and His Work ➖


#include <bits/stdc++.h>
using namespace std;

long long gcd(long long a, long long b) {


while (b) {
a %= b;
swap(a, b);
}
return a;
}

long long calculateHours(vector<int>& arr, int start, int days) {


long long total = 0;
long long g = arr[start];
for (int i = start; i < start + days; i++) {
g = gcd(g, arr[i]);
total += arr[i];
}
return total / g;
}

vector<int> solve(int N, int M, long long K, vector<int> Arr, vector<int>


D) {
vector<int> result;
for (int q = 0; q < M; q++) {
int start = D[q] - 1;
int maxDays = N - start;
if (maxDays <= 0 || (long long)Arr[start] < K) {
long long maxHours = calculateHours(Arr, start, maxDays);
if (maxHours < K) {
result.push_back(-1);
continue;
}
}

int left = 1, right = maxDays;


int ans = maxDays;
while (left <= right) {
int mid = left + (right - left) / 2;
long long hours = calculateHours(Arr, start, mid);
if (hours >= K) {
ans = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
long long hours = calculateHours(Arr, start, ans);
if (hours >= K) {
result.push_back(ans);
} else {
result.push_back(-1);
}
}
return result;
}

6- FENWICK TREE ➖
#include <bits/stdc++.h>
using namespace std;

class FenwickTree {
public:
vector<int> bit;
int size;

FenwickTree(int n) {
size = n;
bit.assign(n + 1, 0);
}

void update(int idx, int delta) {


while (idx <= size) {
bit[idx] += delta;
idx += idx & -idx;
}
}

void range_update(int l, int r, int delta) {


update(l, delta);
update(r + 1, -delta);
}

int query(int idx) {


int sum = 0;
while (idx > 0) {
sum += bit[idx];
idx -= idx & -idx;
}
return sum;
}
};

void dfs(int node, int parent, vector<vector<int>> &adj, vector<int>


&euler, vector<int> &in_time, vector<int> &out_time, int &timer) {
timer++;
in_time[node] = timer;
euler[timer] = node;

for (int child : adj[node]) {


if (child != parent) {
dfs(child, node, adj, euler, in_time, out_time, timer);
}
}

out_time[node] = timer;
}

void solve() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;

vector<vector<int>> adj(n + 1);


for (int i = 0; i < n - 1; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}

vector<int> values(n + 1);


for (int i = 1; i <= n; i++) {
cin >> values[i];
}

int q;
cin >> q;
vector<tuple<int, int, int>> queries(q);
for (int i = 0; i < q; i++) {
int t, x, y;
cin >> t >> x >> y;
queries[i] = {t, x, y};
}

// Step 1: Euler Tour


vector<int> euler(n + 1), in_time(n + 1), out_time(n + 1);
int timer = 0;
dfs(1, -1, adj, euler, in_time, out_time, timer);

// Step 2: Fenwick Tree for subtree updates


FenwickTree bit(n);

// Step 3: Process queries


for (auto [t, x, y] : queries) {
if (t == 1) {
bit.range_update(in_time[x], out_time[x], y);
} else {
bit.range_update(1, n, y);
bit.range_update(in_time[x], out_time[x], -y);
}
}

// Step 4: Compute final values


vector<int> result(n + 1);
for (int i = 1; i <= n; i++) {
int node = euler[i];
result[node] = values[node] + bit.query(in_time[node]);
}

// Output results
for (int i = 1; i <= n; i++) {
cout << result[i] << " ";
}
cout << "\n";
}

int main() {
solve();
return 0;
}

#Fenwick Tree
7- ENERGY NODES CODES ➖
#include <bits/stdc++.h>

using namespace std;

int solve(int N, int M, int K, vector<int> energy, vector<vector<int>>


edges) {
if (N == 1) return 0;

vector<vector<int>> g(N + 1);


for (auto &e : edges) {
g[e[0]].push_back(e[1]);
g[e[1]].push_back(e[0]);
}

vector<int> distOne(N + 1, 1e9);


distOne[1] = 0;

queue<int> q;
q.push(1);
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v : g[u]) {
if (distOne[v] > distOne[u] + 1) {
distOne[v] = distOne[u] + 1;
q.push(v);
}
}
}

if (distOne[N] == (int)1e9) return -1;

vector<int> Idx(N + 1, -1);


int b1 = -1, bN = -1;
for (int i = 0; i < K; i++) {
Idx[energy[i]] = i;
if (energy[i] == 1) b1 = i;
}

bool isBN = false;


if (Idx[N] >= 0) {
bN = Idx[N];
isBN = true;
}

vector<int> own(N + 1, -1), distB(N + 1, 1e9);


queue<int> boosterQueue;

for (int i = 0; i < K; i++) {


own[energy[i]] = i;
distB[energy[i]] = 0;
boosterQueue.push(energy[i]);
}

while (!boosterQueue.empty()) {
int u = boosterQueue.front();
boosterQueue.pop();
for (int v : g[u]) {
if (distB[v] > distB[u] + 1) {
distB[v] = distB[u] + 1;
own[v] = own[u];
boosterQueue.push(v);
}
}
}

vector<long long> distNBooster(K, 1e9);


if (own[N] >= 0) distNBooster[own[N]] = distB[N];

vector<vector<pair<int, int>>> bg(K);


for (auto &e : edges) {
int x = own[e[0]], y = own[e[1]];
if (x >= 0 && y >= 0 && x != y) {
int w = distB[e[0]] + distB[e[1]] + 1;
bg[x].push_back({y, w});
bg[y].push_back({x, w});
}
}

int L = 1, R = distOne[N], ans = -1;


while (L <= R) {
int mid = (L + R) / 2;
vector<bool> vis(K, false);
queue<int> qq;
vis[b1] = true;
qq.push(b1);

bool ok = false;
while (!qq.empty()) {
int u = qq.front();
qq.pop();
if (isBN && u == bN) {
ok = true;
break;
}
for (auto &ed : bg[u]) {
if (ed.second <= mid && !vis[ed.first]) {
vis[ed.first] = true;
if (distNBooster[u] <= mid) {
ok = true;
break;
}
qq.push(ed.first);
}
}
}

if (ok) {
ans = mid;
R = mid - 1;
} else {
L = mid + 1;
}
}

return ans;
}
8- TWO GROUPS ➖
from collections import deque

def solve(N, M, enemy):


# Graph adjacency list
graph = {i: [] for i in range(1, N+1)}

# Build the graph


for u, v in enemy:
graph[u].append(v)
graph[v].append(u)

# To store colors: 0 (not visited), 1 (Group 1), -1 (Group 2)


color = {i: 0 for i in range(1, N+1)}

max_S = 0 # Maximum possible value of S

def bfs(start):
queue = deque([start])
color[start] = 1 # Assign first color

group1, group2 = 1, 0 # Track sizes of the two groups

while queue:
node = queue.popleft()
for neighbor in graph[node]:
if color[neighbor] == 0: # Not visited
color[neighbor] = -color[node] # Assign opposite group
if color[neighbor] == 1:
group1 += 1
else:
group2 += 1
queue.append(neighbor)
elif color[neighbor] == color[node]:
return 0 # Not bipartite

return min(group1, group2) # We need equal-sized groups

# Process all components


for student in range(1, N+1):
if color[student] == 0: # Not visited
S = bfs(student)
if S == 0:
return 0 # If not bipartite, return 0
max_S += S

return max_S

# Example Test Case


N=6
M=4
enemy = [(1, 2), (2, 4), (1, 5), (6, 3)]

print(solve(N, M, enemy))

# TWO GROUPS

9- XOR ON ARRAY ➖
#include <bits/stdc++.h>
using namespace std;
int minimize_difference(int N, vector<int>& A, int K, vector<int>&
operand) {
vector<vector<int>> possible_values(N);

for (int idx = 0; idx < N; ++idx) {


set<int> values;

for (int mask = 0; mask < (1 << K); ++mask) {


int new_value = A[idx];
for (int i = 0; i < K; ++i) {
if (mask & (1 << i)) {
new_value ^= operand[i];
}
}
values.insert(new_value);
}

possible_values[idx] = vector<int>(values.begin(), values.end());


sort(possible_values[idx].begin(), possible_values[idx].end());
}

vector<pair<int, int>> all_values;

for (int i = 0; i < N; ++i) {


for (int value : possible_values[i]) {
all_values.emplace_back(value, i);
}
}

sort(all_values.begin(), all_values.end());

map<int, int> count;


int left = 0, min_range = INT_MAX, distinct_count = 0;

for (int right = 0; right < all_values.size(); ++right) {


int value = all_values[right].first;
int index = all_values[right].second;

if (count[index] == 0) {
++distinct_count;
}
++count[index];

while (distinct_count == N) {
min_range = min(min_range, value - all_values[left].first);
int left_index = all_values[left].second;
--count[left_index];

if (count[left_index] == 0) {
--distinct_count;
}
++left;
}
}

return min_range;
}

BELOW CODES I’M NOT MUCH GUARANTEED SO DO AS YOUR


CHOICE
9- BUDGET PLANNING:-

def Min_budget (N, arr):

arr=sorted(set(arr))

basis=[]

for num in arr:

for bin basis:

num=min(num, num^b)

if num:

basis.append(num)

basis.sort(reverse=True)

return len(basis)

pass

N = int(input())

arr = list(map(int, input().split()))


out_ = Min_budget (N, arr)

print (out_)

You might also like