Skip to content

Commit de4de0e

Browse files
committed
correction
1 parent 38ddb36 commit de4de0e

2 files changed

Lines changed: 28 additions & 18 deletions

File tree

‎Sprint-1/JavaScript/calculateSumAndProduct/calculateSumAndProduct.js‎

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,10 @@
1818
*/
1919
export function calculateSumAndProduct(numbers) {
2020
let sum = 0;
21-
for (const num of numbers) {
22-
sum += num;
23-
}
24-
2521
let product = 1;
22+
2623
for (const num of numbers) {
24+
sum += num
2725
product *= num;
2826
}
2927

@@ -33,9 +31,8 @@ export function calculateSumAndProduct(numbers) {
3331
};
3432
}
3533

36-
// For two loops, we have visit each element of array in order to get the result
37-
// so time complexity is O (n) which means linear.
38-
// Regarding space complexity, we only get one result
39-
// for sum and product no matter how long the array is.so it is O(1)(constant)
40-
// While time complexity is O(n), optimal time complexity should be O(n) because loop
41-
// has to go each single element in array.
34+
// Time complexity is O(n) because we visit each element once.
35+
// Space complexity is O(1) because we use a fixed number of variables,
36+
// regardless of the length of the input array.
37+
// Optimal time complexity is O(n) because every element must be examined
38+
// to guarantee the correct sum and product.

‎Sprint-1/Python/find_common_items/find_common_items.py‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,27 @@ def find_common_items(
99
"""
1010
Find common items between two arrays.
1111
12-
Time Complexity:O(nm)
13-
Space Complexity:O(n+m)
14-
Optimal time complexity:O(n+m)
15-
which is the same as JavaScript const findCommonItems = (firstArray, secondArray)
12+
Approach:
13+
- Convert the second sequence to a set for faster membership checks.
14+
- Use a set to track items already added and avoid duplicates.
15+
- Preserve the order of items as they appear in the first sequence.
16+
17+
Time Complexity: O(n + m) on average, because set lookups take O(1)
18+
on average and we iterate through both sequences.
19+
20+
Space Complexity: O(n + m) as an upper bound for the sets and output.
21+
More precisely, O(m + k), where k is the number of unique common items.
22+
23+
Optimal Time Complexity: O(n + m) on average, assuming hashable items
24+
and constant-time set operations on average.
1625
"""
26+
second_items = set(second_sequence)
1727
common_items: List[ItemType] = []
18-
for i in first_sequence:
19-
for j in second_sequence:
20-
if i == j and i not in common_items:
21-
common_items.append(i)
28+
seen_items = set()
29+
30+
for item in first_sequence:
31+
if item in second_items and item not in seen_items:
32+
common_items.append(item)
33+
seen_items.add(item)
34+
2235
return common_items

0 commit comments

Comments
 (0)