Recently Asked OAs in DE Shaw
Question 1: String Reversal
Question 2
Question 3: Minimum Cost Path:
int n, m;
string s;
cin >> s >> m;
n = s.size();
string ans = s;
int x = m - 1, i = 0;
while (x >= 0) {
ans[x] = s[i++];
x -= 2;
}
x = (m % 2 != 0);
while (x <= m - 2) {
ans[x] = s[i++];
x += 2;
}
cout << ans << endl;
Overview : In this question we have to find the a path form node 0 to node n-1 such that the distance (number of edges) between the nodes are less than of equal to " max edge " and maximum weight among the these edges be minimum.
Approach :
Time Complexity : O(log2(1e9)*(n+m)).
PseudoCode :
void dfs(int node,vi &dis,vi &vis,int val){
vis[node]= 1;
for(pii cur:adj[node]){
int ch = cur.ff,w = cur.ss;
if(w<=val and vis[ch]==0){
dis[ch] = dis[node]+1;
dfs(ch,dis,vis,val);
}
}
}
while(r>=l){
int mid = (r+l)>>1;
vi dis(n,inf),vis(n,0);
dis[0]= 0;
dfs(0,dis,vis,mid);
if(dis[n-1]<=k) ans = mid,r = mid-1;
else l = mid+1;
}
In this question, we are given two integers, num1 and num2 (in form of string, as it can be bigger than integer range) and two integers (minsum and maxsum). Our task is to find the number of integers x s.t. num1 <= x <= num2 and minsum <= sum of digits of x <= maxsum. Length of num1 and num2 <= 100.
Such kinds of problems are more easily solved by digit DP. Hence, using DP, we will try to find the number of integers <= num, having sum of digits <= maxsum. Using this, we can find the number of integers <= num having sum of digits between minsum and maxsum by the following method:
Let f be the result of the dp, then f(num,maxsum) - f(num,minsum-1) will give us required result.
Finding the same for num2 and num1-1 (as we have to remove all integers <= num1-1 from our result in num2), our final answer will just be the difference of f(num,maxsum) - f(num,minsum-1) between 'num2' and 'num1-1'.
The dp is formulated as follows:
O(len(num2)^2) {as sum goes from 0 to 9*len(num2)}.
Contains Dp state and transitions only.
const int maxn=101;
int dp[maxn][2][maxn*10]={};
for(int i = 1;i < n;i++)
{
for(char c = '0';c <= '9';c++)
{
if(c < num[i])
{
int currC=(c-'0');
for(int s=currC;s<=maxsum;s++)
{
dp[i][0][s]+=dp[i-1][1][s-currC]+dp[i-1][0][s-currC];
dp[i][0][s]%=mod;
}
}
else if(c == num[i])
{
int currC=(c-'0');
for(int s=currC;s<=maxsum;s++)
{
dp[i][0][s]+=dp[i-1][1][s-currC]+dp[i-1][0][s-currC];
dp[i][0][s]%=mod;
dp[i][1][s]+=dp[i-1][1][s-currC];
dp[i][1][s]%=mod;
}
}
else{
int currC=(c-'0');
for(int s=currC;s<=maxsum;s++)
{
dp[i][0][s]+=dp[i-1][0][s-currC];
dp[i][0][s]%=mod;
}
}
}
}