fork download
  1. /*
  2. Problem: Evaluate a Nested Math Expression
  3.  
  4. Given a valid expression containing:
  5. add(x,y), sub(x,y), mul(x,y),
  6. div(x,y), pow(x,y)
  7.  
  8. Evaluate the expression and return the integer result.
  9.  
  10. Division truncates toward zero.
  11. Exponents are nonnegative integers.
  12. Spaces may appear around tokens.
  13.  
  14. Example:
  15. Input: "add(5,mul(2,pow(3,2)))"
  16. Output: 23
  17. Time: O(n)
  18. Space: O(d), where d is maximum nesting depth.
  19. Approach: Iterative parsing with two stacks.
  20. */
  21. /*
  22. TIME COMPLEXITY: O(n)
  23.  
  24. Let:
  25. n = length of the expression
  26. k = number of pow() calls
  27. E = maximum exponent
  28.  
  29. 1. Parsing the expression takes O(n) time.
  30.  
  31. 2. Our custom power(base, exp) uses binary exponentiation:
  32.   - It halves exp in every iteration.
  33.   - Therefore, one power() call takes O(log exp) time.
  34.  
  35. 3. Since exponents are nonnegative signed 32-bit integers:
  36.   - Maximum exp = 2^31 - 1 = 2,147,483,647
  37.   - Halving this exponent takes at most 31 iterations.
  38.   - Therefore, each power() call takes O(31) = O(1) time.
  39.  
  40. 4. Even if there are k pow() calls:
  41.   - Total exponentiation work <= 31 * k.
  42.   - Since k <= n, this is O(n).
  43.  
  44. Overall:
  45. O(n + 31*k) = O(n)
  46.  
  47. IMPORTANT:
  48. - O(log exp) describes the custom power() function generally.
  49. - O(1) describes each power() call under the fixed 32-bit constraint.
  50. - If exponents were unbounded, complexity would be
  51.   O(n + k*log E), assuming constant-time arithmetic.
  52.  
  53. SPACE COMPLEXITY: O(d), worst case O(n)
  54.  
  55. d = maximum nesting depth.
  56.  
  57. - names stack stores pending operations.
  58. - values stack stores numbers and intermediate results.
  59. - Each stack uses O(d) space.
  60. - Custom power() uses O(1) extra space.
  61.  
  62. Overall auxiliary space: O(d), worst case O(n).
  63. */
  64. /*
  65. SPACE COMPLEXITY: O(d), worst case O(n)
  66.  
  67. Let:
  68. n = length of the expression (maximum 200,000)
  69. d = maximum nesting depth
  70.  
  71. Example:
  72. add(0,0) -> d = 1
  73. add(0,add(0,0)) -> d = 2
  74. add(0,add(0,add(0,0))) -> d = 3
  75.  
  76. UPPER BOUND OF d:
  77.  
  78. 1. The shortest function call is "add(0,0)",
  79.   which contains 8 characters.
  80.  
  81. 2. Each additional nesting level adds 7 characters:
  82.   "add(0," -> 6 characters
  83.   ")" -> 1 character
  84.  
  85. 3. Therefore, the minimum length for depth d is:
  86.  
  87.   n_min = 8 + 7 * (d - 1)
  88.   = 7d + 1
  89.  
  90. 4. Since n <= 200,000:
  91.  
  92.   7d + 1 <= 200,000
  93.  
  94.   d <= floor((200,000 - 1) / 7)
  95.   d <= 28,571
  96.  
  97.   Maximum possible nesting depth = 28,571.
  98.  
  99. STACK SPACE:
  100.  
  101. - names stack stores at most d pending operations.
  102. - values stack stores at most d + 1 numbers/results.
  103. - Therefore, auxiliary space is O(d).
  104.  
  105. Since d can grow proportionally to n:
  106.  
  107. Worst-case space complexity = O(n).
  108.  
  109. IMPORTANT:
  110. The iterative two-stack solution uses ordinary heap memory,
  111. so it avoids the recursion call-stack overflow that could
  112. occur with recursive DFS at very large nesting depths.
  113. */
  114.  
  115.  
  116. function evaluateExpression(s) {
  117. const names = [];
  118. const values = [];
  119.  
  120. let i = 0;
  121.  
  122. // Skip spaces at the current position.
  123. function skipSpaces() {
  124. while (i < s.length && s[i] === ' ') {
  125. i++;
  126. }
  127. }
  128.  
  129. // Check whether a number begins at index i.
  130. function isNumberStart(ch) {
  131. return ch === '-' || (ch >= '0' && ch <= '9');
  132. }
  133.  
  134. // Read a complete integer, including negative numbers.
  135. function parseNumber() {
  136. const start = i;
  137.  
  138. if (s[i] === '-') {
  139. i++;
  140. }
  141.  
  142. while (
  143. i < s.length &&
  144. s[i] >= '0' &&
  145. s[i] <= '9'
  146. ) {
  147. i++;
  148. }
  149.  
  150. return Number(s.slice(start, i));
  151. }
  152.  
  153. // Read the three-letter operation name.
  154. function parseOperation() {
  155. const operation = s.slice(i, i + 3);
  156. i += 3;
  157. return operation;
  158. }
  159.  
  160. // Apply an operation to two arguments.
  161. function applyCall(operation, x, y) {
  162. if (operation === 'add') return x + y;
  163. if (operation === 'sub') return x - y;
  164. if (operation === 'mul') return x * y;
  165. if (operation === 'div') return Math.trunc(x / y);
  166. if (operation === 'pow') return Math.pow(x, y);
  167. }
  168.  
  169. // Main iterative parsing loop.
  170. while (i < s.length) {
  171. skipSpaces();
  172.  
  173. if (i >= s.length) break;
  174.  
  175. if (isNumberStart(s[i])) {
  176. // Case 1: Number
  177. values.push(parseNumber());
  178.  
  179. } else if (s[i] >= 'a' && s[i] <= 'z') {
  180. // Case 2: Operation
  181. names.push(parseOperation());
  182.  
  183. } else if (s[i] === ')') {
  184. // Case 3: Completed function call
  185. const y = values.pop();
  186. const x = values.pop();
  187. const operation = names.pop();
  188.  
  189. values.push(applyCall(operation, x, y));
  190.  
  191. i++; // Skip ')'
  192.  
  193. } else {
  194. // Case 4: Skip '(' or ','
  195. i++;
  196. }
  197. }
  198.  
  199. return values[0];
  200. }
  201.  
  202. // ---------------- TEST HARNESS ----------------
  203.  
  204. const tests = [
  205. ["add(1,sub(1,0))", 2],
  206. ["add(sub(5,2),sub(1,4))", 0],
  207. ["sub(add(7,8),sub(3,1))", 13],
  208. ["add(5,mul(2,pow(5,2)))", 55],
  209. ["sub(div(-7,2),pow(-2,3))", 5],
  210. ["div(-7,2)", -3],
  211. ["pow(0,0)", 1],
  212. ["add(-12,34)", 22],
  213. ["mul(-3,-4)", 12],
  214. ["42", 42],
  215. ["add( 5 , mul( 2 , 3 ) )", 11]
  216. ];
  217.  
  218. tests.forEach(([input, expected], index) => {
  219. const actual = evaluateExpression(input);
  220.  
  221. console.log(
  222. `Test ${index + 1}: ${actual === expected ? "PASS" : "FAIL"}` +
  223. ` | Expected: ${expected} | Actual: ${actual}`
  224. );
  225. });
  226.  
Success #stdin #stdout 0.03s 5560KB
stdin
Standard input is empty
stdout
Test 1: PASS | Expected: 2 | Actual: 2
Test 2: PASS | Expected: 0 | Actual: 0
Test 3: PASS | Expected: 13 | Actual: 13
Test 4: PASS | Expected: 55 | Actual: 55
Test 5: PASS | Expected: 5 | Actual: 5
Test 6: PASS | Expected: -3 | Actual: -3
Test 7: PASS | Expected: 1 | Actual: 1
Test 8: PASS | Expected: 22 | Actual: 22
Test 9: PASS | Expected: 12 | Actual: 12
Test 10: PASS | Expected: 42 | Actual: 42
Test 11: PASS | Expected: 11 | Actual: 11