
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Array thirds with equal sums in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of integers as the first and the only argument. Our function should return true if and only if we can partition the array into three non-empty parts with equal sums, false otherwise.
For example, if the input to the function is −
const arr = [3, 3, 6, 5, -2, 2, 5, 1, -9, 4];
Then the output should be −
const output = true;
Output Explanation
Because,
3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4
Example
The code for this will be −
const arr = [3, 3, 6, 5, -2, 2, 5, 1, -9, 4]; const thirdSum = (arr = []) => { const sum = arr.reduce((acc, val) => acc + val, 0); if(!Number.isInteger(sum / 3)){ return false; }; let count = 0; let curr = 0; const target = sum / 3; for(const num of arr){ curr += num; if(curr === target){ curr = 0; count += 1; }; }; return count === 3 && curr === 0; }; console.log(thirdSum(arr));
Output
And the output in the console will be −
true
- Related Articles
- Subarray pairs with equal sums in JavaScript
- Can array be divided into n partitions with equal sums in JavaScript
- Prefix sums (Creating an array with increasing sum) with Recursion in JavaScript
- Array index to balance sums in JavaScript
- All combinations of sums for array in JavaScript
- Construct Target Array With Multiple Sums in C++
- Parse array to equal intervals in JavaScript
- Find the sums for which an array can be divided into subarrays of equal sum in Python
- Are array of numbers equal - JavaScript
- Group array by equal values JavaScript
- Finding a number of pairs from arrays with smallest sums in JavaScript
- JavaScript Program for Find k pairs with smallest sums in two arrays
- Split Array with Equal Sum in C++
- Find pairs in array whose sums already exist in array in C++
- Finding minimum steps to make array elements equal in JavaScript

Advertisements