O(N) one pass solution using hashmap
\nclass Solution:\n    from collections import defaultdict\n    def minSumOfLengths(self, arr: List[int], target: int) -> int:\n        prefixSum = defaultdict(
```\nclass Solution:\n    from collections import defaultdict\n    def minSumOfLengths(self, arr: List[int], target: int) -> int:\n        prefixSum = defaultdict(int) # prefix sum dictionary \n        currSum = 0\n        prefixSum[0] = -1 \n        n = len(arr)\n        res = float(\'inf\') # results\n        dp = [float(\'inf\')] * n # dp[i] the length of longest subarray whose sum is target and ends at or before i \n        for i in range(n):\n            currSum += arr[i]\n            restSum = currSum - target\n            if i - 1 >= 0: dp[i] = dp[i-1] \n            if restSum in prefixSum:\n                right,left = i,prefixSum[restSum]+1\n                if left - 1 >= 0:\n                    res = min(res,right - left + 1 + dp[left - 1])\n                dp[i] = min(dp[i],right - left + 1)\n            prefixSum[currSum] = i # update prefix sum dictionary\n        return res if res != float(\'inf\') else -1\n\n```
['Dynamic Programming', 'Prefix Sum', 'Python']