ProgrammingHardTCS NQT · Accenture pattern
What will be the output of the following pseudocode (counting set bits for every number from 0 to n using a DP recurrence)? (>> is right shift, & is bitwise AND.)
What will be the output of the following pseudocode (counting set bits for every number from 0 to n using a DP recurrence)? (>> is right shift, & is bitwise AND.)
Integer n = 5
Integer dp[6] = all zeros
for (each i from 1 to n)
dp[i] = dp[i >> 1] + (i & 1)
end for
Print dp- A. [0, 1, 1, 2, 1, 2]
- B. [0, 1, 2, 1, 2, 1]
- C. [0, 1, 1, 2, 2, 3]
- D. [1, 1, 2, 2, 1, 2]
Correct answer: A. [0, 1, 1, 2, 1, 2]
dp[i] reuses the bit count of i>>1 (i with its last bit dropped) plus whether the last bit is set: dp[1]=dp[0]+1=1, dp[2]=dp[1]+0=1, dp[3]=dp[1]+1=2, dp[4]=dp[2]+0=1, dp[5]=dp[2]+1=2.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode (reversing the order of words in a sentence)? String s = "the sky is blue" List words…
- What will be the output of the following pseudocode (number of ways to make change for an amount using given coin denominations, counting…
- What will be the output of the following pseudocode (length of the longest common SUBSTRING, i.e. contiguous, not subsequence)? Function…
- What will be the output of the following pseudocode (counting distinct ordered character pairs (s[i], s[j]) with i<j)? (Strings are…
- What will be the output of the following pseudocode (capitalizing the first letter of each word, manually)? String s = "hello world foo"…
- What will be the output of the following pseudocode (maximum sum of any 4 consecutive elements, sliding window)? (Arrays are indexed from…