Skip to content

Commit cd6cead

Browse files
authored
Merge pull request #1522 from ivanpenaloza/january20
adding algo
2 parents 9a80565 + 3eda364 commit cd6cead

3 files changed

Lines changed: 116 additions & 0 deletions

File tree

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
4+
class Solution:
5+
6+
def calculate(self, s: str) -> int:
7+
"""
8+
Evaluate a basic calculator expression with +, -, and parentheses.
9+
Uses a stack to handle nested parentheses.
10+
11+
Time: O(n), Space: O(n)
12+
"""
13+
stack = []
14+
result = 0
15+
current_num = 0
16+
sign = 1 # 1 for positive, -1 for negative
17+
18+
for char in s:
19+
if char.isdigit():
20+
# Build multi-digit number
21+
current_num = current_num * 10 + int(char)
22+
elif char == '+':
23+
# Add previous number with its sign
24+
result += sign * current_num
25+
current_num = 0
26+
sign = 1
27+
elif char == '-':
28+
# Add previous number with its sign
29+
result += sign * current_num
30+
current_num = 0
31+
sign = -1
32+
elif char == '(':
33+
# Save current result and sign to stack
34+
stack.append(result)
35+
stack.append(sign)
36+
# Reset for new sub-expression
37+
result = 0
38+
sign = 1
39+
elif char == ')':
40+
# Complete current number
41+
result += sign * current_num
42+
current_num = 0
43+
# Pop sign and previous result from stack
44+
result *= stack.pop() # Apply sign before parenthesis
45+
result += stack.pop() # Add previous result
46+
47+
# Add the last number
48+
result += sign * current_num
49+
50+
return result
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
function calculate(s: string): number {
2+
const stack: number[] = [];
3+
let result = 0;
4+
let currentNum = 0;
5+
let sign = 1; // 1 for positive, -1 for negative
6+
7+
for (const char of s) {
8+
if (char >= '0' && char <= '9') {
9+
// Build multi-digit number
10+
currentNum = currentNum * 10 + parseInt(char);
11+
} else if (char === '+') {
12+
// Add previous number with its sign
13+
result += sign * currentNum;
14+
currentNum = 0;
15+
sign = 1;
16+
} else if (char === '-') {
17+
// Add previous number with its sign
18+
result += sign * currentNum;
19+
currentNum = 0;
20+
sign = -1;
21+
} else if (char === '(') {
22+
// Save current result and sign to stack
23+
stack.push(result);
24+
stack.push(sign);
25+
// Reset for new sub-expression
26+
result = 0;
27+
sign = 1;
28+
} else if (char === ')') {
29+
// Complete current number
30+
result += sign * currentNum;
31+
currentNum = 0;
32+
// Pop sign and previous result from stack
33+
result *= stack.pop()!; // Apply sign before parenthesis
34+
result += stack.pop()!; // Add previous result
35+
}
36+
// Skip spaces
37+
}
38+
39+
// Add the last number
40+
result += sign * currentNum;
41+
42+
return result;
43+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import unittest
2+
from src.my_project.interviews.top_150_questions_round_22\
3+
.ex_54_basic_calculator import Solution
4+
5+
class BasicCalculatorTestCase(unittest.TestCase):
6+
7+
def test_first_pattern(self):
8+
solution = Solution()
9+
output = solution.calculate(s = "1 + 1")
10+
target = 2
11+
self.assertEqual(output, target)
12+
13+
def test_second_pattern(self):
14+
solution = Solution()
15+
output = solution.calculate(s = " 2-1 + 2 ")
16+
target = 3
17+
self.assertEqual(output, target)
18+
19+
def test_third_pattern(self):
20+
solution = Solution()
21+
output = solution.calculate(s = "(1+(4+5+2)-3)+(6+8)")
22+
target = 23
23+
self.assertEqual(output, target)

0 commit comments

Comments
 (0)