Skip to main content

Posts

Showing posts from August, 2019

16 3Sum Closest Leetcode Problem Javascript Solution

16. 3Sum Closest Medium Given an array  nums  of  n  integers and an integer  target , find three integers in  nums  such that the sum is closest to  target . Return the sum of the three integers. You may assume that each input would have exactly one solution. Example: Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). Here is a Javascript Solution to the 3Sum Closest Problem from Leetcode: const threeSum = (arr, sum) => { const ilength = arr.length-2; const jlength = ilength+1; let total; let closest = Infinity; let diff = Math.abs(closest - sum); for(let i=0, j=i+1, k=j+1; i<ilength; i++, j++, k++) { total = arr[i]+arr[j]+arr[k]; if (diff > (Math.abs(total - sum))) { closest = total; if (closest === sum) { break; } diff = Math.abs(closest - sum); } if (j<jlength) { i--; } else...

Find all groups of three values from an array that add up to the given value

Find all groups of three values from an array that add up to the given value const threeSum = ( arr , sum ) => { const ans = []; const ilength = arr . length - 2 ; const jlength = ilength + 1 ; let check = false ; for ( let i = 0 , j = i + 1 , k = j + 1 ; i < ilength ; i ++, j ++, k ++) { if ( arr [ i ]+ arr [ j ]+ arr [ k ] === sum ) { ans . push ([ arr [ i ], arr [ j ], arr [ k ]]); } if ( j < jlength ) { i --; } else { j = i + 1 ; } if ( k < arr . length ) { j --; } else { k = j + 1 ; } } return ans ; } Test Input console . log ( threeSum ([- 1 , 0 , 1 , 2 , - 1 , - 4 , - 3 , 5 , - 6 , 0 ], 4 )) Output [ [ - 1 , 0 , 5 ], [ - 1 , 5 , 0 ], [ 0 , - 1 , 5 ], [ 2 , - 3 , 5 ], [ - 1 , 5 , 0 ] ] Run the code here:  https://repl.it/@VinitKhandelwal/15-leetcode-3sum

14 Longest Common Prefix Leetcode Problem Javascript Solution

Longest Common Prefix Easy Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string  "" . Example 1: Input: ["flower","flow","flight"] Output: "fl" Example 2: Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings. Note: All given inputs are in lowercase letters  a-z . Javascript Solution to the Longest Common Prefix Problem const longestPrefix = arr => { if (arr.length === 0) { return ""; } if (arr.length === 1) { return arr[0]; } let end = 0; let check = false for (let j = 0; j < arr[0].length; j++){ for (let i = 1; i < arr.length; i++) { if (arr[0][j] !== arr[i][j]) { check = true; break; } } if (check) { break; } end++; } return (ar...