Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Convert Infix To Prefix Notation

Medium Acceptance 52.94% Points 30.00

You are given an infix expression as a string s and need to convert it into a postfix expression.

  1. Infix Expression: This is the standard mathematical notation where operators are placed between operands, e.g., a op b (e.g., a + b).
  2. Postfix Expression: This is a format where the operator follows the operands, e.g., a b op (e.g., a b +).

Note: Follow the operator precedence:

  • ^ has the highest precedence.
  • * and / have equal precedence, which is higher than + and -.
  • For simplicity, ignore the right associativity of ^.
Examples
Example 1

Example 1

Input: s = "x+y*z"

Output: xyz*+

Explanation: * has higher precedence than +, so y*z is evaluated first. The postfix expression becomes xyz*+.

Example 2

Example 2

Input: s = "a*b+c/d"

Output: ab*cd/+

Explanation: * and / have the same precedence, so a*b and c/d are evaluated first, followed by +. The postfix expression is ab*cd/+.

Hints
Hint 1
Expected Time Complexity: O(n)
Hint 2
Expected Auxiliary Space: O(n)
Constraints
  • 1 <= s.length <= 30
Companies
Microsoft Visa Paytm
Topics
Stack
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions