C# - O(N) Sliding Window, find all intervals, pick two non overlapping smallest
Update:  We can maintain minimum length so far at each array index so when sum == target, we can look up if there is length encountered which is minimum as well
**Update**:  We can maintain minimum length so far at each array index so when sum == target, we can look up if there is length encountered which is minimum as well as non-overlapping by checking the value at index `start - 1`\n\n```csharp\npublic int MinSumOfLengths(int[] arr, int target)\n{\n\tint[] minLengths = new int[arr.Length];\n\tfor (int i = 0; i < arr.Length; i++)\n\t{\n\t\tminLengths[i] = int.MaxValue;\n\t}\n\n\tint sum = 0;\n\tint start = 0;\n\tint result = int.MaxValue;\n\tint currentMinLength = int.MaxValue;\n\n\tfor (int end = 0; end < arr.Length; end++)\n\t{\n\t\tsum += arr[end];\n\n\t\twhile (sum > target)\n\t\t{\n\t\t\tsum -= arr[start];\n\t\t\tstart++;\n\t\t}\n\n\t\tif (sum == target)\n\t\t{\n\t\t\tint currentLength = end - start + 1;\n\n\t\t\tif (start > 0 && minLengths[start - 1] != int.MaxValue)\n\t\t\t{\n\t\t\t\tresult = Math.Min(result, minLengths[start - 1] + currentLength);\n\t\t\t}\n\n\t\t\tcurrentMinLength = Math.Min(currentMinLength, currentLength);\n\t\t}\n\n\t\tminLengths[end] = currentMinLength;\n\t}\n\n\treturn result == int.MaxValue ? -1 : result;\n}\n```\n\nBelow is original incorrect solution - min length may not be correct as first pick since for test cases like [1,1,3,2,1,1,1]  - it would pick(3, 2) and block (1,1,3) (2,1,1,1) as lengths to be considered giving no solution.\n\n```csharp\npublic int MinSumOfLengths(int[] arr, int target) \n{\n\tList<(int Start, int End, int Length)> lengths = new List<(int, int, int)>();\n\tint sum = 0;\n\tint start = 0;\n\n\tfor(int end = 0; end < arr.Length; end++)\n\t{\n\t\tsum += arr[end];\n\n\t\twhile(sum > target && start <= end)\n\t\t{\n\t\t\tsum -= arr[start];\n\t\t\tstart++;\n\t\t}\n\n\t\tif(sum == target)\n\t\t{\n\t\t\tlengths.Add((start, end, end - start + 1));\n\t\t}\n\t}\n\n\tif(lengths.Count < 2)\n\t{\n\t\treturn -1;\n\t}\n\n\tlengths = lengths.OrderBy(x => x.Length).ToList();\n\tvar first = lengths[0];\n\tforeach(var len in lengths)\n\t{\n\t\tif(len.Start > first.End || len.End < first.Start)\n\t\t{\n\t\t\treturn first.Length + len.Length;\n\t\t}\n\t}\n\n\treturn -1;\n}\n```
[]