Problem Statement:
We have a sorted array and the task is checking each array elements and identify the first two elements which sum is zero and print the first pair only.
CODE in C :
//checking sun zero
//[-11,-5,-3,0,2,5,6] => input
#include <stdio.h>
int main(){
int array[7]={-11,-5,-3,0,2,5,6};
int size = sizeof(array) / sizeof(int);
for(int p=0;p<size;p++){
for(int i=1;i<size;i++){
if((array[p]) + (array[i]) == 0){
printf("output:[%d,%d]\n",array[p],array[i]);
return 0;
}
}
}
}
//output:[-5,5]
CODE in JavaScript:
//checking sum zero
//[-11,-5,-3,0,2,5,6] => input
function getSumPairZero(array){
for(let number of array){
// console.log("Outer loop")
for(let j=1;j<array.length;j++){
// console.log("inner loop")
if(number + array[j] === 0){
return[number , array[j]];
}
}
}
}
const result=getSumPairZero([-11,-5,-3,0,2,5,6]);
console.log(result);
-------------------------------------------------------------------------------
OUTPUT: [ -5, 5 ]
--------------------------------------------------------------------------------
>> This program use nested loop so,
Time complexity : O(n^2)
{quadratic} 🔚🔚🔚🔚🔚🔚🔚🔚🔚🔚🔚🔚🔚🔚🔚🔚🔚🔚🔚🔚
🔰 For same problem, if we write optimal code,
then time Complexity will be O(n), which is linear.
✅The logic is here 🢃
Code in JavaScript:
//checking sum zero
//[-11,-5,-3,0,2,5,6] => input
//but here our intension is optimize the code and
//the time complexity is less than the previous logic.
function getSumPairZero(array){
let left=0;
let right=array.length-1;
while(left<right){
sum=array[left]+array[right];
if(sum===0){
return [ array[left] , array[right] ];
}
else if(sum>0){
right--;
}
else{
left++;
}
}
}
const result=getSumPairZero([-11,-5,-3,0,2,5,6]);
console.log(result);
//O(n) linear time complexity
-------------------------------------------------------------------------------
OUTPUT: [ -5, 5 ]
--------------------------------------------------------------------------------
Comments
Post a Comment