How to find the length of the longest balanced parentheses (e.g. (()())) in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>

int longest_valid_parentheses(const char *s) {
    int n = strlen(s);
    int stack[n + 1];      // stack of indices
    int top = 0;
    int max_len = 0;

    stack[top] = -1;       // base index

    for (int i = 0; i < n; i++) {
        if (s[i] == '(') {
            stack[++top] = i;
        } else { // s[i] == ')'
            top--;        // pop
            if (top < 0) {
                // stack empty → new base
                top = 0;
                stack[top] = i;
            } else {
                int len = i - stack[top];
                if (len > max_len)
                    max_len = len;
            }
        }
    }

    return max_len;
}

int main(void) {
    const char *s = "((()()))((("; // balanced parentheses = ((()())) then length = 8
    printf("%d\n", longest_valid_parentheses(s));  
    
    return 0;
}



/*
run:

8

*/

 



answered Dec 24, 2025 by avibootz
edited Dec 24, 2025 by avibootz
...