I was given this question during an interview. It is similar to two sum problems and I would like to ask for feedback for my solution.
Merging 2 Packages
Given a package with a weight limit limit and an array arr of item weights, implement a function getIndicesOfItemWeights that finds two items whose sum of weights equals the weight limit limit. Your function should return a pair [i, j] of the indices of the item weights, ordered such that i > j. If such a pair doesn’t exist, return an empty array.
Example:
input: arr = [4, 6, 10, 15, 16], lim = 21
output: [3, 1] # since these are the indices of the # weights 6 and 15 whose sum equals to 21 Constraints:
[time limit] 5000ms
[input] array.integer arr
0 ≤ arr.length ≤ 100 [input] integer limit
[output] array.integer
function getIndicesOfItemWeights(arr, limit) { let weights = {}; let result = [] for ( let i = 0; i < arr.length; i++){ let compliment = limit - arr[i]; if (typeof weights[compliment]!= "undefinded"){ if (i > (weights[compliment])){ result.push(weights[compliment], i); //return [i, weights[compliment]]; } else { return [weights[compliment] , i]; } } else { weights[arr[i]] = i; // put new weight into weight obj } } return []; } let arr = [4, 6, 10, 15, 16]; let limit = 21; console.log(getIndicesOfItemWeights(arr, limit)) // output: [3, 1] # since these are the indices of the // weights 6 and 15 whose sum equals to 21
[undefined, 0]
- should it actually log[3, 1]
?\$\endgroup\$[undefined, 0]
instead of[3, 1]
. The commented outreturn
statement looks suspicious, so is the typo "undefinded" (instead ofundefined
)\$\endgroup\$