Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 3, 2022 07:47 am GMT

sumZero with O(n) in Javascript.

Given a sorted array. Write a function sumZero and return the first found pair otherwise undefined.

cases:

sumZero([-3,-2,-1,0,1,2,3]); // [-3,3];
sumZero([0,1,2,3]); // undefined
sumZero([-3,1,2]); // undefined

function sumZero(arr) {    let left = 0;    let right = arr.length - 1;    while (left < right) {        const result = arr[left] + arr[right];        if (result === 0) return [arr[left], arr[right]];        result < 1 ? left++ : right--;    }}

Thanks.

Love to see your response

  1. Like - You reached here means. I think, I deserve a like.
  2. Comment - We can learn together.
  3. Share - Makes others also find this resource useful.
  4. Subscribe / Follow - to stay up to date with my daily articles.
  5. Encourage me - You can buy me a Coffee

Let's discuss further.

  1. Just DM @urstrulyvishwak
  2. Or mention
    @urstrulyvishwak

For further updates:

Follow @urstrulyvishwak


Original Link: https://dev.to/urstrulyvishwak/sumzero-with-on-in-javascript-2126

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To