Ternary Expression Parser in C++

Suppose we have a string representing arbitrarily nested ternary expressions, we have to calculate the result of the expression. we can always assume that the given expression is valid and only consists of digits 0-9, ?, :, T and F these few characters. (Here T and F represent True and False respectively). There are some properties −

  • The length of the given string must be less than or equal to 10000.

  • Each number will contain only one digit.

  • The conditional expressions group right-to-left.

  • The condition will always be either T or F. So the condition will never be a digit.

  • The result of the expression will always evaluate to either a digit 0-9, T or F.

So for example, if the input is like “F?1:T?4:5”, so the output will be 4, as it will parse the rightmost expression “T?4:5”, it will return 4, then the main expression will be “F?1:4”, so the returned value is 4.

To solve this, we will follow these steps −

  • ret := an empty string, n := size of s, create a stack st

  • for I in range n – 1 down to 0

    • x := s[i]

    • if st is not empty and top of stack is ‘?’, then

      • delete from st

      • first := top of st, then delete two elements from the stack

      • second := top of the stack, and delete from st

      • if x is T, then insert first into st, otherwise insert second into st

    • otherwise, insert x into st

  • while st is not empty, then

    • ret := ret + top of st and delete from st

  • reverse ret and return ret

Example (C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   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() == '?'){
            char first = st.top();
            char second = st.top();
            if(x == 'T'){
            else st.push(second);
            ret += st.top();
         reverse(ret.begin(), ret.end());
      return ret;
   Solution ob;
   cout << (ob.parseTernary("F?1:T?4:5"));





Updated on: 29-Apr-2020


Kickstart Your Career

Get certified by completing the course

Get Started