1. Dynamic Array Substring Replacement
Intuition
Maintain an explicit dynamic array of token strings. Whenever an operator is seen, collapse the preceding 2 elements into a parenthesized string.
Algorithm
- Step 1: Loop through each character
cinexp. - Step 2: If
cis alphanumeric, appendcto list. - Step 3: If
cis operator, remove last two itemsbanda, format(a + c + b), and append to list. - Step 4: Return the only remaining item in list.
#include <iostream>#include <string>#include <vector> class Solution {public: std::string postToInfix(std::string exp) { std::vector<std::string> list; for (char c : exp) { if (isalnum(c)) { list.push_back(std::string(1, c)); } else { std::string b = list.back(); list.pop_back(); std::string a = list.back(); list.pop_back(); list.push_back("(" + a + c + b + ")"); } } return list.front(); }}; int main() { Solution solver; std::cout << "Infix: " << solver.postToInfix("ab*c+") << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Repeated string concatenation and array allocations scale quadratically with expression length. - Space complexity:
O(N)— O(N) space for intermediate strings.
Why Brute Force Doesn't Scale:
Splice operations on large token lists become quadratic.
Stack approach converts 10,000 characters in <3ms.