PPractick

DSA interview question

Postfix to Prefix Conversion

Medium · Data structures · Topics: stack, string

The problem

A stack-machine assembler writes expressions in postfix (for example ABC/-AK/L-*), but a symbolic-math library it feeds requires prefix (*-A/BC-/AKL). Postfix is read naturally left to right: operands are pushed, and when an operator arrives its two operands are already on the stack, right on top, left below. Pop them in that order and push op + left + right.

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

Function signature

string postfixToPrefix(const string& post);  // single-character operands; binary operators

Test cases

InputOutputExplanation
ABC/-AK/L-**-A/BC-/AKL
ab++ab
ab+cd-**+ab-cd
ab+c--+abc
aa

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

How interviewers phrase it

Clarifying questions to ask

  1. Are all operators binary? (Yes.)
  2. Single-character operands?
  3. Is the input valid? (Otherwise check the stack sizes.)

Follow-ups to expect

  1. "Why left to right here?"
  2. "Which pop is which?"
  3. "How do you detect invalid input?"
  4. "How does this relate to evaluating postfix?"
  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