diff --git a/src/_Problems_/find-2-nums-adding-to-n/index.js b/src/_Problems_/find-2-nums-adding-to-n/index.js index 0f6fbeb1..5ba3e0a7 100644 --- a/src/_Problems_/find-2-nums-adding-to-n/index.js +++ b/src/_Problems_/find-2-nums-adding-to-n/index.js @@ -1,32 +1,32 @@ -// the best case using a data structure - SET -function findTwoNumsAddingToN(arr, sum) { - const nums = []; +// the best case [O(n)] using SET data structure +function findTwoNumsAddingToN(arr, number) { + const pair = []; const store = new Set(); - for (let i = 0; i < arr.length; i++) { - // check if the set contains one of the pir that sum upto given sum - if (store.has(sum - arr[i])) { - nums.push(sum - arr[i]); - nums.push(arr[i]); + for (let i = 0; i < arr.length; i += 1) { + // check if the set contains one of the element that sum upto the given number + if (store.has(number - arr[i])) { + pair.push(number - arr[i]); + pair.push(arr[i]); break; } // push the element in the set store.add(arr[i]); } - return nums.length ? nums : false; + return pair.length ? pair : false; } // the Brute force approach -function findTwoNumsAddingToN2(arr, sum) { - const nums = []; - for (let i = 0; i < arr.length; i++) { - for (let j = i + 1; j < arr.length; j++) { - if (arr[i] + arr[j] === sum) { - nums.push(arr[i], arr[j]); +function findTwoNumsAddingToN2(arr, number) { + const pair = []; + for (let i = 0; i < arr.length; i += 1) { + for (let j = i + 1; j < arr.length; j += 1) { + if (arr[i] + arr[j] === number) { + pair.push(arr[i], arr[j]); break; } } } - return nums.length ? nums : false; + return pair.length ? pair : false; } diff --git a/src/_Problems_/find-2nd-max/index.js b/src/_Problems_/find-2nd-max/index.js new file mode 100644 index 00000000..0cbb2433 --- /dev/null +++ b/src/_Problems_/find-2nd-max/index.js @@ -0,0 +1,22 @@ +/** + * You may find it easy but it's tricky for few + * Input - [9, 2, 3, 6] + * Output - 6 + */ + +function findSecondMax(arr) { + let max = arr[0]; + let max2 = Number.MIN_SAFE_INTEGER; + + for (let el of arr) { + if (el > max) { + max2 = max; + max = el; + } + + if (el < max && el > max2) { + max2 = el; + } + } + return max2; +}