Python / Rust - Prefix Sum
Python\n\npython\nclass Solution:\n    def minSumOfLengths(self, arr: List[int], target: int) -> int:\n        s, lsize, res = 0, float(\'inf\'), float(\'inf\')
-  **Python**\n\n```python\nclass Solution:\n    def minSumOfLengths(self, arr: List[int], target: int) -> int:\n        s, lsize, res = 0, float(\'inf\'), float(\'inf\')\n        prefixSum = { 0: -1 }\n        \n        for i, val in enumerate(arr):\n            s += val\n            prefixSum[s] = i\n            \n        s = 0\n        for i, val in enumerate(arr):\n            s += val\n            \n            if s - target in prefixSum:\n                lsize = min(i - prefixSum[s - target], lsize)\n            \n            if s + target in prefixSum and lsize != float(\'inf\'):\n                rsize = prefixSum[s + target] - i\n                res = min(res, rsize + lsize)\n                \n        return res if res != float(\'inf\') else -1\n```\n\n- **Rust**\n\n```rust\nuse std::collections::HashMap;\n\nimpl Solution {\n    pub fn min_sum_of_lengths(arr: Vec<i32>, target: i32) -> i32 {\n        let (mut sum, mut res, mut lsize) = (0, std::i32::MAX, std::i32::MAX);\n        let mut prefixSum: HashMap<i32, i32> = HashMap::new();\n        \n        prefixSum.insert(0, -1);\n        \n        for (i, val) in arr.iter().enumerate() {\n            sum += *val;\n            prefixSum.insert(sum, i as i32);\n        }\n        \n        sum = 0;\n        for (i, val) in arr.iter().enumerate() {\n            sum += *val;\n            let index = i as i32;\n            \n            if prefixSum.contains_key(&(sum - target)) {\n                lsize = lsize.min(index - *prefixSum.get(&(sum - target)).unwrap());\n            }\n            \n            if prefixSum.contains_key(&(sum + target)) && lsize != std::i32::MAX {\n                let rsize = *prefixSum.get(&(sum + target)).unwrap() - index;\n                res = res.min(rsize + lsize);\n            }\n        }\n        \n        return if res == std::i32::MAX { -1 } else { res }\n    }\n}\n```
['Dynamic Programming', 'Prefix Sum', 'Python', 'Rust']