Program to evaluate ternary expression in C++

Looking at this article, I can see it's about C++ but labeled as Python. I'll improve the structure, fix the HTML issues, and make it clearer while keeping the C++ content intact.

A ternary expression uses the format condition ? value1 : value2. Given a string representing nested ternary expressions with 'T' (True) and 'F' (False), we need to evaluate the final result.

Problem Constraints

  • String length ? 10000
  • Conditional expressions group right-to-left
  • Conditions are always 'T' or 'F', never digits
  • Final result is always 'T' or 'F'

For example, "T?T?F:T:T" evaluates to "F".

Algorithm

We use a stack-based approach, processing the expression from right to left:

  1. Traverse the string from right to left
  2. When we encounter a '?' on the stack top, we have a complete ternary expression
  3. Pop the condition, first value, colon, and second value
  4. Push the result based on the condition
  5. Continue until the entire expression is evaluated

Example

Let's trace through "T?T?F:T:T":

#include <iostream>
#include <stack>
#include <string>
#include <algorithm>
using namespace std;

class Solution {
public:
    string parseTernary(string s) {
        string ret = "";
        int n = s.size();
        stack<char> st;
        
        for(int i = n - 1; i >= 0; i--){
            char x = s[i];
            if(!st.empty() && st.top() == '?'){
                st.pop();
                char first = st.top();
                st.pop();
                st.pop(); // Remove ':'
                char second = st.top();
                st.pop();
                if(x == 'T'){
                    st.push(first);
                } else {
                    st.push(second);
                }
            } else {
                st.push(x);
            }
        }
        
        while(!st.empty()){
            ret += st.top();
            st.pop();
        }
        reverse(ret.begin(), ret.end());
        return ret;
    }
};

int main(){
    Solution ob;
    cout << ob.parseTernary("T?T?F:T:T") << endl;
    return 0;
}

How It Works

The expression "T?T?F:T:T" is processed as follows:

  1. Start from right: Push 'T', ':', 'T', '?', 'F', '?', 'T', '?', 'T'
  2. When we see 'T' and stack top is '?', we evaluate the inner ternary
  3. Inner expression: T ? F : T ? Result is 'F'
  4. Continue with outer expression: T ? F : T ? Result is 'F'

Output

F

Time Complexity

Time: O(n) where n is the length of the input string

Space: O(n) for the stack

Conclusion

This stack-based approach efficiently evaluates nested ternary expressions by processing them right-to-left. The algorithm handles the right-associative nature of ternary operators correctly.

Updated on: 2026-03-25T12:48:58+05:30

376 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements