Loading Similar Posts
Question 1
Overview:
Approach:
i
) , for all 1<=i<=1e9
priority_queue <data_type, vector<data_type>, greater<data_type>> variable_name;
{Start_i,end_i}
.1
to the number of currently running processes.priority_queue
, in the form of {end_i,start_i}
start_i
.- If yes, pop and reduce the number of currently running processes by `1`.
- If no break
Complexity:
O(NLOGN),
where is N
is a number of processes.Pseudocode:
int getMinCores(vector<int> start, vector<int> end)
{
vector<pair<int, int>> p;
for (int i = 0; i < start.size(); i++)
{
p.push_back({start[i], end[i]});
}
sort(p.begin(), p.end());
int count = 0;
int ans = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
for (int i = 0; i < p.size(); i++)
{
q.push({p[i].second, p[i].first});
count++;
while (!q.empty() && q.top().first < p[i].first)
{
q.pop();
count--;
}
ans = max(ans, count);
}
return ans;
}
Portfolio Backtesting is a repeated question. Previously asked for Standard Chartered. Checkout the solution below.
Solution Link here: Portfolio Backtesting
Question 3
Overview
x,y,z
, find the number of nodes i
whose distances from x,y,z
sorted in ascending order form a Pythagorean tripletx!=y
,x!=z
, y!=z
), we also take (i!=x!
, i!=y
, i!=z
)approach
:
i
(i!=x!
, i!=y
, i!=z
) and sort those distances from z,y,z and check whether they for a Pythagorean tripletComplexity
O(N)
N is the number of NodesO(N+M)
, but for a tree M=N-1
, so DFS complexity is O(N)
Pseudocode
void dfs(vector<vector<int>> &adj, vector<vector<int>> &dist, vector<bool> &vis, int u, int dfsnumber)
{
vis[u] = true;
for (auto v : adj[u])
if (!vis[v])
{
dist[v].push_back(dist[u][dfsnumber] + 1);
dfs(adj, dist, vis, v, dfsnumber);
}
}
int countPythogoreanTriplets(int treenodes, vector<int> tree_from, vector<int> tree_to, int x, int y, int z)
{
vector<vector<int>> adj(treenodes);
vector<vector<int>> dist(treenodes);
vector<bool> vis(treenodes, false);
for (int i = 0; i < treenodes - 1; i++)
{
adj[tree_from[i]].push_back(tree_to[i]);
adj[tree_to[i]].push_back(tree_from[i]);
}
dist[x].push_back(0);
dfs(adj, dist, vis, x, 0);
for (int i = 0; i < treenodes; i++)
vis[i] = false;
dist[y].push_back(0);
dfs(adj, dist, vis, y, 1);
for (int i = 0; i < treenodes; i++)
vis[i] = false;
dist[z].push_back(0);
dfs(adj, dist, vis, z, 2);
int ans = 0;
for (int i = 0; i < treenodes; i++)
if (i != x && i != y && i != z)
{
sort(dist[i].begin(), dist[i].end());
if ((dist[i][0] * dist[i][0] + dist[i][1] * dist[i][1]) == dist[i][2] * dist[i][2])
ans++;
}
return ans;
}