Longest balanced entry exit stretch

Write codeMedium16 min

Your task

A ward's door sensor writes one character per event: 'I' when someone enters, 'O' when someone leaves. For a staffing report, find the length of the longest contiguous stretch of events containing exactly as many entries as exits. Return 0 if no such stretch exists. The input contains only 'I' and 'O' characters and may be empty. Example: events = "IOOI" gives 4, since the whole log has two entries and two exits.

Examples

longest_balanced_stretch(events: str) -> int
Example 1
Inputlongest_balanced_stretch("IOOI")
Output4