Grokking Data Structures & Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Exanubes
Cleaner solution in javascript

Exanubes

Jun 10, 2024

class Solution { findDifferenceArray(nums) { const n = nums.length; const differenceArray = new Array(n).fill(0); let right = nums.reduce((acc,curr)=>acc+curr, 0) let left = 0; for(let i = 0; i<nums.length; i++) { right-= nums[i] differenceArray[i] = Math.abs(left - right); left+= nums[i] } // TODO: Write your code here return differenceArray; } }

I think we can just sum all the numbers and then iteratively subtract from right and add to left. The solution is done in two passes instead of three and saves space by not creating additional arrays for left and right. It's less complicated too

1

0

Comments
Comments
Mario Lopez
Mario Lopez8 months ago

This makes sense but is there a better solution? That can do it in one pass?

On this page

Problem Statement

Examples

Solution

Step-by-step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity