Skip to content

Commit c35f4b4

Browse files
committed
perf(py): optimize calculate_sum_and_product (2n → n)
1 parent c3881bf commit c35f4b4

File tree

1 file changed

+36
-6
lines changed

1 file changed

+36
-6
lines changed

Sprint-1/Python/calculate_sum_and_product/calculate_sum_and_product.py

Lines changed: 36 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,20 +12,50 @@ def calculate_sum_and_product(input_numbers: List[int]) -> Dict[str, int]:
1212
"sum": 10, // 2 + 3 + 5
1313
"product": 30 // 2 * 3 * 5
1414
}
15-
Time Complexity:
16-
Space Complexity:
17-
Optimal time complexity:
15+
16+
Time Complexity: O(n) - Single pass through the list
17+
Space Complexity: O(1) - Only using constant extra space
18+
Optimal Time Complexity: O(n) - Cannot do better than linear time
1819
"""
20+
# OPTIMIZED IMPLEMENTATION: O(n) time complexity
21+
# Previous implementation: O(2n) due to two separate loops
22+
23+
sum_total = 0 # O(1) space
24+
product = 1 # O(1) space
25+
26+
# O(n) time complexity
27+
for current_number in input_numbers:
28+
sum_total += current_number # O(1)
29+
product *= current_number # O(1)
30+
31+
return {"sum": sum_total, "product": product}
32+
33+
34+
# ORIGINAL IMPLEMENTATION (for comparison):
35+
"""
36+
def calculate_sum_and_product(input_numbers: List[int]) -> Dict[str, int]:
1937
# Edge case: empty list
2038
if not input_numbers:
2139
return {"sum": 0, "product": 1}
2240
2341
sum = 0
24-
for current_number in input_numbers:
42+
for current_number in input_numbers: # First pass: O(n)
2543
sum += current_number
2644
2745
product = 1
28-
for current_number in input_numbers:
46+
for current_number in input_numbers: # Second pass: O(n)
2947
product *= current_number
3048
31-
return {"sum": sum, "product": product}
49+
return {"sum": sum, "product": product} # Total: O(2n) = O(n) time
50+
51+
COMPLEXITY ANALYSIS OF ORIGINAL:
52+
- First loop: O(n) iterations to calculate sum
53+
- Second loop: O(n) iterations to calculate product
54+
- Total: O(2n) = O(n) time complexity
55+
- Space: O(1) - only using loop variables
56+
57+
IMPROVEMENTS MADE:
58+
1. Reduced from 2n to n operations (50% fewer iterations)
59+
2. Single pass through list instead of two separate loops
60+
3. Same O(n) time complexity but with better constant factors
61+
"""

0 commit comments

Comments
 (0)