Got asked these in Walmart coding round:
A. Given a number n. To find two numbers a and b such that
a xor b = n
b >= a and (b - a) should be minimum
for all the a and b which satisfy the above conditions a and b should be minimum
1 <= n <= 1e12
- My Soln:
for(j = 0; j <= 62; j++)
if((n >> j) & 1) b = (1 << j);
a = n - b;
- Result: Partial testcase passed
- Weightage: 20 pts.
B. Given an array A of size n and a number K. Have to find the number of subarrays [l, r] such that:
(r - l + 1) = K * (sum of all elements of subarray [l, r])
1 <= n <= 1e5
|K| >= 1
-1e6 <= A[i] <= 1e6
- My Soln: Wrote O(n * n) soln. Spoiler Alert got TLE.
- Weightage: 30 pts.
How can I have solved these???
For the 2nd problem
Equation 1) Sum of a subarray[l, r] -> prefixSum[r] — prefixSum[l-1]
Equation 2) r — l + 1 = (k * prefix_sum[r]) — (k * prefix_sum[l-1])
Equation 3) r — (k * prefix_sum[r]) = l — 1 — (k * prefix_sum[l-1])
So, first, calculate, prefix_sums and intiliaze prefix_sum[-1] = 0
Now, maintain an occurence table for the right side of the equation 3 above. For this purpose, you can use an
unordered_map
orordered_map
.After that, iterate from left-to-right and for each index increment the occurence by 1, for the following expression -> (i — 1 — (k * prefix_sum[i-1])) (Right side of the 3rd equation)
Lastly, for each index i, update the answer by frequency of the following expression -> (i — (k * prefix_sum[i]))(Left side of the 3rd equastion)
Thanks, bro. I appreciate it.
For A, you can give the largest set bit to b, while other set bits to a. Unset bits should be set to 0 for both. I think that should work. Correct me if I am wrong
yes, that's correct
I did the same but it didn't passed all the test cases.
Problem in your code is that when you are calling b = (1 << j); then , overflow occurs. To avoid this use (1LL << j) this will convert int 1 to long long 1 and prevent overflow.
Thanks bro. It worked.
WELP , I misread it,I thought K*(r-l+1)=sum of elements in the range, sorry for trouble.
No problem. Thanks though.
Problem B Solution
Thanks, bro. I appreciate it.