networking · beginner · ~15 min

Active connections

Track concurrent connection count.

Challenge

Replay a log of connect/disconnect events and report how many clients are still connected at the end. Each character in the log is 'c' (a client connected) or 'd' (a client disconnected).

Task

Implement int active_connections(const char *ops) that returns the number of clients connected after processing ops left to right. A 'd' when nobody is connected is ignored (the count never goes negative).

Input

A string ops of 'c' and 'd' characters.

Output

Returns the active connection count at the end.

Example

active_connections("ccdc")   ->   2
active_connections("cd")     ->   0
active_connections("dd")     ->   0   (disconnects with no one connected are ignored)

Edge cases

  • A 'd' with a zero count does not decrement below 0.

Input format

A string ops of 'c' (connect) and 'd' (disconnect) characters.

Output format

The number of clients still connected at the end.

Constraints

Increment on 'c'; decrement on 'd' only when the count is > 0.

Starter code

int active_connections(const char *ops) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.