To make the brute force more efficient, we will be using a very popular data structure named: Hash Table.
A hash table keeps a key-value pair in a table using a hash function. As the hash function directly returns the memory address of the value given a key, its search, insert, and delete operations are in constant O(1) time.
We will be using a hash table to store the cumulative sum of the array as a key and its ending elements index as the value.
xxxxxxxxxx39
var assert = require('assert');function subarraySum(nums, n) { // hash of prefix sums // Fill in this method return nums;}const arr = [1, 2, 3], sum = 5;console.log(subarraySum(arr, sum));try { assert.equal(subarraySum([1, 2, 3], 3), true); console.log('PASSED: ' + 'assert.equal(subarraySum([ 1, 2, 3 ], 3), true)');} catch (err) { console.log(err);}try { assert.equal(subarraySum([], 3), false); console.log('PASSED: ' + 'assert.equal(subarraySum([], 3), false)');} catch (err) { console.log(err);OUTPUT
Results will appear here.