|
1 | 1 | /** |
2 | 2 | * Find if there is a pair of numbers that sum to a given target value. |
3 | 3 | * |
4 | | - * Time Complexity: |
5 | | - * Space Complexity: |
6 | | - * Optimal Time Complexity: |
| 4 | + * Time Complexity: O(n) - Single pass through the array |
| 5 | + * Space Complexity: O(n) - Set to store seen numbers |
| 6 | + * Optimal Time Complexity: O(n) - Cannot do better than linear time |
7 | 7 | * |
8 | 8 | * @param {Array<number>} numbers - Array of numbers to search through |
9 | 9 | * @param {number} target - Target sum to find |
10 | 10 | * @returns {boolean} True if pair exists, false otherwise |
11 | 11 | */ |
12 | 12 | export function hasPairWithSum(numbers, target) { |
13 | | - for (let i = 0; i < numbers.length; i++) { |
14 | | - for (let j = i + 1; j < numbers.length; j++) { |
15 | | - if (numbers[i] + numbers[j] === target) { |
16 | | - return true; |
17 | | - } |
| 13 | + // OPTIMIZED IMPLEMENTATION: O(n) time complexity |
| 14 | + // Previous implementation: O(n²) due to nested loops |
| 15 | + |
| 16 | + const seen = new Set(); // O(n) |
| 17 | + |
| 18 | + // O(n) time complexity |
| 19 | + for (const num of numbers) { |
| 20 | + const complement = target - num; |
| 21 | + // O(1) lookup |
| 22 | + if (seen.has(complement)) { |
| 23 | + return true; |
18 | 24 | } |
| 25 | + |
| 26 | + // O(1) operation |
| 27 | + seen.add(num); |
19 | 28 | } |
20 | 29 | return false; |
21 | 30 | } |
| 31 | +console.log(hasPairWithSum([3, 2, 3, 4, 5], 9)); |
| 32 | +/* |
| 33 | + * ORIGINAL IMPLEMENTATION (for comparison): |
| 34 | + * |
| 35 | + * export function hasPairWithSum(numbers, target) { |
| 36 | + * for (let i = 0; i < numbers.length; i++) { // O(n) iterations |
| 37 | + * for (let j = i + 1; j < numbers.length; j++) { // O(n) iterations each |
| 38 | + * if (numbers[i] + numbers[j] === target) { // O(1) comparison |
| 39 | + * return true; |
| 40 | + * } |
| 41 | + * } |
| 42 | + * } |
| 43 | + * return false; |
| 44 | + * } |
| 45 | + * |
| 46 | + * COMPLEXITY ANALYSIS OF ORIGINAL: |
| 47 | + * - Outer loop: O(n) iterations |
| 48 | + * - Inner loop: O(n) iterations for each outer iteration |
| 49 | + * - Total: O(n²) time complexity |
| 50 | + * - Space: O(1) - only using loop variables |
| 51 | + * |
| 52 | + * PERFORMANCE ISSUES: |
| 53 | + * - Quadratic time complexity O(n²) |
| 54 | + * |
| 55 | + * IMPROVEMENTS MADE: |
| 56 | + * 1. Reduced from O(n²) to O(n) time complexity |
| 57 | + * 2. Single pass through array instead of nested loops |
| 58 | + * 3. Set lookup is O(1) vs nested iteration O(n) |
| 59 | + */ |
0 commit comments