I am trying to solve a problem in GeeksClasses and I am having an issue with my submission. My code works but they are saying Your program took more time than expected.
problem link: https://practice.geeksforgeeks.org/problems/find-triplets-with-zero-sum/1/?track=SPCF-Sorting&batchId=154
Problem statement:
Given an array of integers. Check whether it contains a triplet that sums up to zero.
Input:
The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. The first line of each test case contains an integer N, denoting the number of elements in array. The second line of each test case contains N space separated values of the array.
Output
For each test case, output will be 1 if triplet exists else 0
Expected Auxiliary Space: O(1)
Expected Time Complexity: O(n2)
Example:
Input:
2
5
0 -1 2 -3 1
3
1 2 3
Output:
1
0
Here is my code
def isPair(arr,left,right,u):
while left < right:
if arr[left] + arr[right] < u:
left += 1
elif arr[left] + arr[right] == u:
return True
elif arr[left] + arr[right] > u:
right -= 1
return False
def findTriplets(a,n):
#code here
a = sorted(a)
for i in range(n):
if isPair(a,i+1,n-1,0-a[i]):
return 1
return 0
#driver code
if __name__=='__main__':
t=int(input())
for i in range(t):
n=int(input())
a=list(map(int,input().strip().split()))
print(findTriplets(a,n))