PPractick

DSA interview question

Infix to Prefix Conversion

Medium · Data structures · Topics: stack, string

The problem

A symbolic-algebra tool stores formulas in prefix notation (operator first), but users type ordinary infix like x+y*z/w+u. The classic conversion reuses the infix-to-postfix algorithm in a mirror: reverse the infix string, swap ( and ), run the shunting-yard with the associativity rule flipped, and reverse the result. The flip matters: in the mirrored string, left-associative operators must not pop equal-precedence operators, while right-associative ^ must.

Example: x+y*z/w+u → ++x/*yzwu.

Function signature

string infixToPrefix(const string& s);  // single-character operands; + - * / ^ and parentheses

Test cases

InputOutputExplanation
x+y*z/w+u++x/*yzwu((x + ((y*z)/w)) + u)
A*(B+C)/D/*A+BCD(A*(B+C))/D
(a+b)*(c-d)*+ab-cd
a-b+c+-abcLeft-associative: (a−b)+c
a^b^c^a^bcRight-associative: a^(b^c)

(Confirm: operands are single characters; the expression is valid; precedence ^ > * / > + −, and only ^ is right-associative.)

How interviewers phrase it

Clarifying questions to ask

  1. Which operators, and what precedence and associativity?
  2. Single-character operands?
  3. Is the input guaranteed valid?

Follow-ups to expect

  1. "Why reverse the string?"
  2. "Why swap the parentheses?"
  3. "Why flip the equal-precedence rule?"
  4. "Alternative approach?"
  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