File tree Expand file tree Collapse file tree
Sprint-1/JavaScript/hasPairWithSum Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11/**
22 * Find if there is a pair of numbers that sum to a given target value.
33 *
4- * Time Complexity:
5- * Space Complexity:
6- * Optimal Time Complexity:
7- *
4+ * Time Complexity: O(n²)
5+ * Space Complexity: O(1)
6+ * Optimal Time Complexity: O(n)
7+ * Explanation: The function uses a nested loop to check every possible pair of numbers in the array
8+ * to see if they sum up to the target value.
9+ * This results in a time complexity of O(n²) because for each number in the array,
10+ * we are checking it against every other number.
11+ *The refactored version uses a Set to check for the existence of the complement, reducing the overall complexity to O(n).
812 * @param {Array<number> } numbers - Array of numbers to search through
913 * @param {number } target - Target sum to find
1014 * @returns {boolean } True if pair exists, false otherwise
1115 */
1216export 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- }
17+ const seen = new Set ( ) ;
18+ for ( const num of numbers ) {
19+ const complement = target - num ;
20+ if ( seen . has ( complement ) ) {
21+ return true ;
1822 }
23+ seen . add ( num ) ;
1924 }
2025 return false ;
2126}
You can’t perform that action at this time.
0 commit comments