File tree Expand file tree Collapse file tree 1 file changed +27
-5
lines changed
Sprint-1/JavaScript/hasPairWithSum Expand file tree Collapse file tree 1 file changed +27
-5
lines changed Original file line number Diff line number Diff line change 99 * @param {number } target - Target sum to find
1010 * @returns {boolean } True if pair exists, false otherwise
1111 */
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+ // }
18+ // }
19+ // }
20+ // return false;
21+ // }
22+
23+ //My Analysis Result
24+ // Time Complexity - since it have two nested loop of the same size/growth here i have a growth of O(n * n) = O(n**2) .. quadratic growth
25+ // Space Complexity - I didnt see any assigning/modifying stored data scenario so i think the space complexity is just O(1) for the return statement
26+ //The inefficiency of this program is due to the nested loop : it creates redudndant checks to compare the numbers.
27+
28+ //here is the refactored code avoiding that redundancy
29+
1230export 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- }
31+ const seenNumbers = new Set ( ) ;
32+ for ( const num of numbers ) {
33+ const complement = target - num ;
34+ if ( seenNumbers . has ( complement ) ) {
35+ return true ; // We found a pair!
1836 }
37+ seenNumbers . add ( num ) ;
1938 }
2039 return false ;
2140}
41+ //here time complexity is reduced to optimal level . just one loop which is O(n)
42+ //for the space complexity here i have O(n) as well because of the Set() i used.
43+ //i traded space to have an optimal time complexity
You can’t perform that action at this time.
0 commit comments