Interactive Problems

Interactive problems rely on the communication of two programs: one that you write the other that the problem author writes. Your program needs to interact with the problem author’s program to solve the problem described in the statement.

Here is an example of what an interactive problem would be like:

Flushing Output

To ensure that anything your program outputs reach the driver program written by the problem author (and is not held in any internal buffer) you need to flush your output.

Every programming language has its own way of dealing with this. Below you can find some examples.


When using printf(), "\n" causes the output buffer to be flushed:

printf("Hello Toph!\n");

To force flush the output buffer, fflush() can be used on stdout:

printf("A 1520 ");

Buffering on stdout can be disabled entirely by using setbuf():

setbuf(stdout, NULL);


When using cout, endl causes the output buffer to be flushed:

cout << "Hello Toph!" << endl;

Alternatively you can use flush:

cout << "Hello Toph!" << flush;

If you prefer using printf in C++, you will have to use fflush() on stdout (even with newline character in the format specification):

printf("Hello Toph!\n");

Or, disable buffering on stdout entirely using setbuf():

setbuf(stdout, NULL);

Python 2

You do not need to do anything extra as long as you are using print without any trailing comma.

Python 3, PyPy 3

You do not need to do anything extra as long as you are using print() without end="".

Example Solutions (of An Obvious Interactive Problem)

C++ Solution

#include <stdio.h>

int main() {
  setbuf(stdout, NULL);

  int L = 0, R = 1000000;
  while(true) {
    int M = (L+R)/2;
    printf("%d\n", M);

    char X[10];
    scanf("%s", X);
    if(X[2] == 'g') // Bigger
      L = M;
    else if(X[2] == 'a') // Smaller
      R = M;
    else if(X[2] == 'n') // Bingo!
  return 0;

Python Solution

L = 0
R = 1000000

while True:
    M = int((L+R)/2)
    X = input()
    if X == 'Bigger':
        L = M
    elif X == 'Smaller':
        R = M
    elif X == 'Bingo!':