-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArraySum.js
More file actions
53 lines (42 loc) · 813 Bytes
/
ArraySum.js
File metadata and controls
53 lines (42 loc) · 813 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Q - Checking Sum Zero in the Array
// arr = [-5, -4, -3, -2, 0, 2, 4, 6, 8] => Input
// O(n^2) quradict time complexity
function CheckArraySum(arr)
{
for (ele of arr) {
for (let i = 1; i < arr.length; i++)
{
if (ele + arr[i] === 0)
{
return [ele, arr[i]]
}
}
}
}
let result = CheckArraySum([-5, -4, -3, -2, 0, 2, 4, 6, 8])
console.log(result)
// there is another logic but this logic only work with sorted Array
// O(n) linear time complexity
function linerCheckArray(arr)
{
let left = 0
let right = arr.length - 1
while(left < right)
{
sum = arr[left] + arr[right]
if(sum === 0)
{
return [arr[left], arr[right]]
}
else if(sum > 0)
{
right--;
}
else
{
left++;
}
}
}
let ans = linerCheckArray([-5, -4, -3, -2, 0, 2, 4, 6, 8])
console.log(ans)