PPractick

DSA interview question

Prefix to Postfix Conversion

Medium · Data structures · Topics: stack, string

The problem

A compiler pipeline receives expressions in prefix form from one tool and must hand them to a stack-based evaluator that expects postfix. Both notations are parenthesis-free and unambiguous, so no precedence rules are involved. Only the operator placement moves. Scan the prefix string right to left: push operands; for an operator, pop the left operand (top) and the right operand, and push left + right + op.

Example: *-A/BC-/AKL → ABC/-AK/L-*.

Function signature

string prefixToPostfix(const string& pre);  // single-character operands; binary operators

Test cases

InputOutputExplanation
*-A/BC-/AKLABC/-AK/L-*
+abab+
*+ab-cdab+cd-*
-+abcab+c-
aa

(Confirm: the prefix expression is valid; operands are single characters; all operators are binary.)

How interviewers phrase it

Clarifying questions to ask

  1. Only binary operators? (Yes.)
  2. Single-character tokens? (Yes; otherwise tokenise first.)
  3. Is the input guaranteed valid?

Follow-ups to expect

  1. "Why right to left?"
  2. "Which pop is the left operand?"
  3. "Why is no precedence needed?"
  4. "Can you do it without strings?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in