Created
March 24, 2021 04:38
-
-
Save aryapreetam/3b6cdfbc9b5d89a24e53e8780b820966 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // given sorted array of numbers, find pair that sums to the target OR is closest to the target number | |
| function findPair(a: number[], target: number): number[][]{ | |
| let start = 0; | |
| let end = a.length - 1 | |
| let result: number[][] = [] | |
| // if we have two values that are at the same distance from the target, | |
| // then array will contain both values, else it will only contain value that is nearer | |
| let nearByValues: number[][] = [] | |
| let diff = Number.MAX_SAFE_INTEGER | |
| while(start < end){ | |
| let startVal = a[start] | |
| let endVal = a[end] | |
| let sum = startVal + endVal | |
| if(sum === target){ | |
| result.push([startVal, endVal]) | |
| start++; | |
| end--; | |
| }else if(sum > target){ | |
| end-- | |
| }else { | |
| start++ | |
| } | |
| let currentMin = Math.min(Math.abs(target - sum), diff) | |
| if(currentMin < diff){ | |
| nearByValues.length = 0; | |
| nearByValues.push([startVal, endVal]) | |
| diff = currentMin | |
| }else if(currentMin === diff){ | |
| nearByValues.push([startVal, endVal]) | |
| } | |
| } | |
| return result.length === 0 ? nearByValues : result; | |
| } | |
| console.log(findPair([2,4,5,6,7,9], 10)) | |
| console.log(findPair([2,4,7,9,11], 10)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment