DEV Community

Cover image for Data Structures & Algorithms in JavaScript -- PS-1.
Shaik Dawood
Shaik Dawood

Posted on

Data Structures & Algorithms in JavaScript -- PS-1.

Given an array, find the first pair whose sum is equal to zero?

Input = [-5, -4, -3, -2, 0, 2, 4, 6, 8].

Output = [-4, 4].

Solution:
Check the given array is sorted or not. If not sort the array.

Approach 1:

We need to traverse the each and every element of the array and compare it with other elements of the array.
We have to apply two loops in it. The first loop (outer one) will start traversing from 0 index of the array and the second loop (inner one ) will start traversing from 1 index of the array. If the sum of 0th index of array and 1st index of array is equal to ZERO then return the pair.
By using this approach we will get Quadratic Time Complexity O(n²).
Alt Text

Approach 2:

Let's assume to variables and assign them with 0 index and last index of array:

  • let left = 0;
  • let right = array.length - 1 ; We need to run a single loop in which we will check if the sum of the left index value and right index value of the given array is equal to Zero, then return that Pair. If sum (left, right) > 0 then decrement the right variable (right--). If sum (left, right) < 0 then increment the left variable(left++). By this approach we can get the Pair of Sum Zero in only one loop. Alt Text

By using this approach we will get Linear Time Complexity O(n).

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay