Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Js solution needs some corrections

Daniil

Dec 18, 2023

In solution by JavaScript i found some initial parameters, with which solution becomes incorrect. This parameters are: Input: [91, 74, 73, 85, 73, 81, 87], target: 230. Current solution returns 231, which is not right because it is bigger than target. Replacing this fragment from solution:

if (Math.abs(target_diff) < Math.abs(smallest_difference) || (Math.abs(target_diff) === Math.abs(smallest_difference) && target_diff > smallest_difference)) { smallest_difference = target_diff; // save the closest and the biggest difference

}

with this fragment:

if ( targetDiff >= 0 && (Math.abs(targetDiff) < Math.abs(smallestDifference) || ( Math.abs(targetDiff) === Math.abs(smallestDifference) && targetDiff > smallestDifference ))) { smallestDifference = targetDiff; }

makes final result more correct. The difference is in this condition: targetDiff >= 0

0

0

Comments
Comments
S
Salah Osman2 years ago

The original function aimed to find the closest sum to the target sum, either greater or smaller. Your modified change, focuses on finding the closest sum that is not greater than the target sum.

Running your change gives 228 but the original solution provides 231 and...

On this page

Problem Statement

Solution

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity