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
  1. A. [0, 1, 1, 2, 1, 2]
  2. B. [0, 1, 2, 1, 2, 1]
  3. C. [0, 1, 1, 2, 2, 3]
  4. 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.

More Pseudocode and Code Tracing questions

Exams that ask this topic