<|instruction|>
Solve the below problem. The solution should start with an abridged problem statement. Then key observations. Then full solution based on the observations. Then C++ and Python implementations with comments.

538. Emoticons
Time limit per test: 1 second(s)
Memory limit: 262144 kilobytes
input: standard
output: standard



A berland national nanochat Bertalk should always stay up-to-date. That's why emoticons highlighting was decided to be introduced. As making emoticons to be highlighted is not exactly the kind of task one performs everyday but this task had to be done as soon as possible, the following simple rule was decided to be introduced: a round opening or closing bracket  be considered part of an emoticon if:
this is an opening bracket and there exists the nearest bracket following to the right. The nearest round bracket to the right should be a closing bracket and there shouldn't be anything between the brackets but spaces and Latin letters,
or else it can be a closing bracket and there exists the nearest round bracket following to the left. The nearest round bracket to the left should be an opening bracket. Besides, there shouldn't be anything between the brackets but spaces and Latin letters.


If a bracket doesn't satisfy the conditions, it is considered a part of an emoticon. For example, let's consider the string "Hi:) (it is me) I have bad news:-((". In the string only the brackets that outline "it is me" aren't emoticons. Note that an opening bracket immediatelly followed by a closing bracket, i.e. "()", are not parts of emoticons by definition.

Your task is to print the number of brackets that are parts of emoticons in the given string.

Input
The input data consist of a single non-empty string. The length of the string does not exceed 105 characters. The string consists of lowercase and uppercase Latin letters, spaces, round brackets and punctuation marks: "-", ":", ",", ";". The string does not begin with and does not end with a space.

Output
Print a single number — the required number of brackets that are part of emoticons.

Example(s)
sample input
sample output
Hi:) (it is me) I have bad news:-((
3 

sample input
sample output
((two plus two equals four)) 
2

<|response|>
1. Abridged Problem Statement  
You are given a string s of length up to 10^5 consisting of letters, spaces, round brackets ‘(’, ‘)’, and a few punctuation marks (`-`, `:`, `,`, `;`).  
We say a bracket is **normal** (i.e., not part of an emoticon) if:  
  - It is ‘(’ and its **nearest** round bracket to the right is ‘)’, and all characters strictly between them are only letters or spaces.  
  - Or it is ‘)’ and its **nearest** round bracket to the left is ‘(’, with only letters or spaces in between.  
All other parentheses are considered parts of emoticons.  
Output the total count of emoticon parentheses in s.

2. Key Observations  
- We need, for each position i, the index of the nearest bracket to the left (`prev_bracket[i]`) and to the right (`next_bracket[i]`).  
- We must quickly check if the substring between two brackets contains **only** letters/spaces. Any other character (punctuation or another bracket) disqualifies them from being a normal pair.  
- We can build a prefix‐sum array `bad[i]` that counts the number of “forbidden” characters (anything except letters or spaces) up to index i. Then the count of forbidden chars in any interval [l..r] is `bad[r] - bad[l-1]`.  
- If we initially assume **all** parentheses are emoticons, we can later detect each “normal” bracket and subtract it from our count.

3. Full Solution Approach  
a. Preprocessing in O(n):  
   1. Build `prev_bracket[]`: in a left-to-right pass, record the most recent index of ‘(’ or ‘)’ up to each position.  
   2. Build `bad[]`: also in that pass, maintain a running total of characters that are **not** letters or spaces (i.e. punctuation or brackets).  
   3. Build `next_bracket[]`: in a right-to-left pass, record the next index of ‘(’ or ‘)’ at or after each position.  

b. Counting emoticons:  
   1. Let `ans =` total number of '(' plus ')'.  
   2. Scan the string again. For each index i:  
      - If `s[i] == '('`, let `j = next_bracket[i]`.  
        Check all of:  
          • `j != -1` and `s[j] == ')'`.  
          • `prev_bracket[j] == i` (ensures they are each other’s nearest).  
          • No forbidden chars between i+1 and j-1, i.e. `bad[j-1] - bad[i] == 0`.  
        If true, this ‘(’ is **normal** → decrement `ans`.  
      - Similarly, if `s[i] == ')'`, let `j = prev_bracket[i]` and apply the symmetric checks.  

c. Print `ans` at the end.

Time complexity: O(n).  
Memory: O(n).

4. C++ Implementation with Detailed Comments  
```cpp
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    string s;
    getline(cin, s);
    int n = s.size();

    // prev_bracket[i]: index of the nearest '(' or ')' at or before i
    vector<int> prev_bracket(n, -1);
    // next_bracket[i]: index of the nearest '(' or ')' at or after i
    vector<int> next_bracket(n, -1);
    // bad[i]: count of forbidden characters up to index i
    // (forbidden = not letter, not space)
    vector<int> bad(n, 0);

    // Build prev_bracket[] and bad[] in one left-to-right pass
    for (int i = 0; i < n; i++) {
        // Update prev_bracket
        if (s[i] == '(' || s[i] == ')') {
            prev_bracket[i] = i;
        } else if (i > 0) {
            prev_bracket[i] = prev_bracket[i - 1];
        }

        // Update bad[]
        bool isForbidden = !( (s[i] >= 'A' && s[i] <= 'Z')
                            || (s[i] >= 'a' && s[i] <= 'z')
                            || s[i] == ' ');
        bad[i] = (i > 0 ? bad[i - 1] : 0) + (isForbidden ? 1 : 0);
    }

    // Build next_bracket[] in a right-to-left pass
    for (int i = n - 1; i >= 0; i--) {
        if (s[i] == '(' || s[i] == ')') {
            next_bracket[i] = i;
        } else if (i + 1 < n) {
            next_bracket[i] = next_bracket[i + 1];
        }
    }

    // Helper to count forbidden chars in s[l..r], inclusive
    auto count_bad = [&](int l, int r) {
        if (l > r) return 0;
        return bad[r] - (l > 0 ? bad[l - 1] : 0);
    };

    // Start by counting every parenthesis as part of an emoticon
    int ans = 0;
    for (char c : s) {
        if (c == '(' || c == ')') ans++;
    }

    // Subtract 1 for each normal bracket
    for (int i = 0; i < n; i++) {
        if (s[i] == '(') {
            int j = next_bracket[i];
            if (j != -1 && s[j] == ')' &&
                prev_bracket[j] == i &&
                count_bad(i + 1, j - 1) == 0)
            {
                ans--;
            }
        }
        else if (s[i] == ')') {
            int j = prev_bracket[i];
            if (j != -1 && s[j] == '(' &&
                next_bracket[j] == i &&
                count_bad(j + 1, i - 1) == 0)
            {
                ans--;
            }
        }
    }

    cout << ans << "\n";
    return 0;
}
```

5. Python Implementation with Detailed Comments  
```python
import sys

def count_emoticons(s: str) -> int:
    n = len(s)
    # nearest bracket to the left/right
    prev_b = [-1] * n
    next_b = [-1] * n
    # bad[i]: number of forbidden chars up to index i
    bad = [0] * n

    # Build prev_b[] and bad[] in one pass
    for i, ch in enumerate(s):
        # nearest bracket to the left
        if ch in '()':
            prev_b[i] = i
        elif i > 0:
            prev_b[i] = prev_b[i - 1]

        # forbidden if not letter, not space
        is_forbidden = not (ch.isalpha() or ch == ' ')
        bad[i] = (bad[i - 1] if i > 0 else 0) + (1 if is_forbidden else 0)

    # Build next_b[] in reverse
    for i in range(n - 1, -1, -1):
        if s[i] in '()':
            next_b[i] = i
        elif i + 1 < n:
            next_b[i] = next_b[i + 1]

    # helper to count forbidden chars in s[l..r]
    def count_bad(l, r):
        if l > r:
            return 0
        return bad[r] - (bad[l - 1] if l > 0 else 0)

    # start by assuming every parenthesis is an emoticon
    ans = sum(1 for ch in s if ch in '()')

    # subtract each normal bracket
    for i, ch in enumerate(s):
        if ch == '(':
            j = next_b[i]
            if (j != -1 and s[j] == ')' and prev_b[j] == i
                and count_bad(i + 1, j - 1) == 0):
                ans -= 1
        elif ch == ')':
            j = prev_b[i]
            if (j != -1 and s[j] == '(' and next_b[j] == i
                and count_bad(j + 1, i - 1) == 0):
                ans -= 1

    return ans

if __name__ == "__main__":
    s = sys.stdin.readline().rstrip('\n')
    print(count_emoticons(s))
```