diff --git a/Sprint-1/JavaScript/calculateSumAndProduct/calculateSumAndProduct.js b/Sprint-1/JavaScript/calculateSumAndProduct/calculateSumAndProduct.js index ce738c3..8060b10 100644 --- a/Sprint-1/JavaScript/calculateSumAndProduct/calculateSumAndProduct.js +++ b/Sprint-1/JavaScript/calculateSumAndProduct/calculateSumAndProduct.js @@ -9,22 +9,22 @@ * "product": 30 // 2 * 3 * 5 * } * - * Time Complexity: - * Space Complexity: - * Optimal Time Complexity: - * + * Time Complexity:O(n) + * Space Complexity:o(1) + * Optimal Time Complexity:o(n) + *The original implementation used two separate loops. + *This refactor combines them into a single loop to reduce + *the constant factor, while maintaining the same Big-O complexity. + * @param {Array} numbers - Numbers to process * @returns {Object} Object containing running total and product */ export function calculateSumAndProduct(numbers) { let sum = 0; - for (const num of numbers) { - sum += num; - } - let product = 1; for (const num of numbers) { product *= num; + sum += num; } return { diff --git a/Sprint-1/JavaScript/hasPairWithSum/hasPairWithSum.js b/Sprint-1/JavaScript/hasPairWithSum/hasPairWithSum.js index dd2901f..61e7c9c 100644 --- a/Sprint-1/JavaScript/hasPairWithSum/hasPairWithSum.js +++ b/Sprint-1/JavaScript/hasPairWithSum/hasPairWithSum.js @@ -1,21 +1,30 @@ /** * Find if there is a pair of numbers that sum to a given target value. * - * Time Complexity: - * Space Complexity: - * Optimal Time Complexity: - * + * Time Complexity:before refactoring O(n²)- after refactoring O(n log n) + * Space Complexity:before refactoring O(1)- after refactoring O(1) + * Optimal Time Complexity:O(n log n) + * https://www.hellointerview.com/learn/code/two-pointers/overview + * The refactored solution first sorts the array, which takes O(n log n) time, + * and then uses the two-pointer technique to scan the array in a single pass (O(n)). The sorting step dominates the overall complexity. * @param {Array} numbers - Array of numbers to search through * @param {number} target - Target sum to find * @returns {boolean} True if pair exists, false otherwise */ export function hasPairWithSum(numbers, target) { - for (let i = 0; i < numbers.length; i++) { - for (let j = i + 1; j < numbers.length; j++) { - if (numbers[i] + numbers[j] === target) { - return true; - } - } + numbers.sort((a,b)=>a-b); + let left=0; + let right=numbers.length-1; + while (left List[ItemType]: """ Find common items between two arrays. - Time Complexity: - Space Complexity: - Optimal time complexity: + Time Complexity:O(n + m) + Space Complexity:O(n + m) + Optimal time complexity:O(n + m) """ - common_items: List[ItemType] = [] - for i in first_sequence: - for j in second_sequence: - if i == j and i not in common_items: - common_items.append(i) - return common_items + second_set=set(second_sequence) + first_set=set(first_sequence) + common_set=first_set.intersection(second_set) + return list(common_set)