ProgrammingHardProduct company OA

What is printed?

What is printed?
int ok(const char *s, int d) {
    if (d < 0) return 0;
    if (!*s) return d == 0;
    return ok(s + 1, d + (*s == '(') - (*s == ')'));
}
int main(void) {
    printf("%d%d%d%d", ok("(()())", 0), ok("())(", 0), ok("((", 0), ok("", 0));
}
  1. A. 1000
  2. B. 0001
  3. C. 1101
  4. D. 1001

Correct answer: D. 1001

d tracks open brackets. "(()())" never goes negative and ends at 0 → 1. "())(" drops to −1 at the third character and fails even though its counts balance → 0. "((" ends at 2 → 0. The empty string ends at 0 → 1. '1101' checks only the totals.

More C Programming questions

Exams that ask this topic