ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (All variables are integers, so / is integer division)

What will be the output of the following pseudocode? (All variables are integers, so / is integer division)
Function canSplit(Integer a[], Integer n)
    Integer total = sum of a
    if (total mod 2 == 1) return false
    Boolean ok[0..total / 2] = all false
    ok[0] = true
    for (each i from 0 to n - 1)
        for (each s from total / 2 down to a[i])
            ok[s] = ok[s] OR ok[s - a[i]]
        end for
    end for
    return ok[total / 2]
End Function
Print canSplit({1, 5, 11, 5}, 4), canSplit({1, 2, 3, 5}, 4), canSplit({2, 2, 3, 5}, 4)
  1. A. true false true
  2. B. true false false
  3. C. true true false
  4. D. false false false

Correct answer: B. true false false

The subset-sum table checks whether half the total can be reached. {1, 5, 11, 5}: 11 = 1 + 5 + 5, true. {1, 2, 3, 5}: total 11 is odd, false. {2, 2, 3, 5}: half is 6, but no subset sums to 6 (2+2 = 4, 2+3 = 5, 2+2+3 = 7…), false. Output true false false.

More Pseudocode and Code Tracing questions

Exams that ask this topic