constpairDifference=(nums)=>{constresults=[]if(!nums||nums.length<2)returnresultsnums.sort()for(leti=0;i<nums.length-1;i++){// 2nd num can only be 1 or 2 positions away when sorted and no duplicatesif(nums[i+1]-nums[i]===2){results.push([nums[i],nums[i+1]])}elseif(i<nums.length-2&&nums[i+2]-nums[i]===2){results.push([nums[i],nums[i+2]])}}returnresults}constpairsEqual=(p1,p2)=>p1[0]===p2[0]&&p1[1]===p2[1]consttest=(nums,expected)=>{constresults=pairDifference(nums)constpassed=results.length===expected.length&&!results.find((p,i)=>!pairsEqual(p,expected[i]))console.log(`${passed?'Pass':'FAIL'} - input: ${JSON.stringify(nums)} `+`expected: ${JSON.stringify(expected)} results: ${JSON.stringify(results)}`)}test([1,2,3,4],[[1,3],[2,4]])test([1,3,4,6],[[1,3],[4,6]])test([4,1,2,3],[[1,3],[2,4]])test([1,23,3,4,7],[[1,3]])test([4,3,1,5,6],[[1,3],[3,5],[4,6]])test(undefined,[])test([],[])test([1],[])test([2,-1,0,1],[[-1,1],[0,2]])test([2000,-100,-98,1999],[[-100,-98]])
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
JS solution