Hello,
I have submitted a solution to a medium difficulty problem.
The problem's question is the following:
subarray-sum-equals-k
The test cases are all passed until a certain point where the input is large. I executed my code on my own IDE and it did find a solution, but it took a while.
This is my code:
class Solution:
def subarraySum(self, nums: list, k: int) -> int:
# checking for satisfaction of all constraints
if (len(nums) == 0) or (len(nums) > (20000)) or not (self.doesKSatisfyConstraint(k) and self.doArrayNumbersSatisfyNumberConstraint(nums)):
return 0
if len(nums) == 1 and k == nums[0]:
return 1
elif len(nums) == 1 and k != nums[0]:
return 0
arraySizeBeingChecked: int = 1
if sum(nums) == k:
numberOfSubarraysEqualToK: int = 1
else:
numberOfSubarraysEqualToK: int = 0
while arraySizeBeingChecked != len(nums):
checkStartPoint: int = 0
while (arraySizeBeingChecked + checkStartPoint) <= len(nums):
if sum(nums[checkStartPoint:arraySizeBeingChecked + checkStartPoint]) == k:
numberOfSubarraysEqualToK += 1
checkStartPoint += 1
arraySizeBeingChecked += 1
return numberOfSubarraysEqualToK
# checking for satisfaction of second constraint
def doArrayNumbersSatisfyNumberConstraint(self, array) -> bool:
# this limit is calculated using the first two constraints:
# 1. the array length min value is 1 and max value is 20000 (2 * 10**4)
# 2. the limit on any array element is less than or equal to 1000 and greater than or equal to -1000
if sum(array) < -20000000 or sum(array) > 20000000:
return False
return True
# checking for satisfaction of third constraint
def doesKSatisfyConstraint(self, k: int) -> bool:
if k < -10 ** 7 or k > 10 ** 7:
return False
return Truewhat can I do? should I rewrite the code to improve the time complexity? if so, then it should be mentioned in the question constraints, which was not in my case.