703396. Sum of Lengths of Non-Overlapping SubArrays

Easy

Sum of Lengths of Non-Overlapping SubArrays

Slug: sum-of-lengths-of-non-overlapping-subarrays2237

Difficulty: Easy

Id: 703396

Topic Tags: Arrays, Data Structures

Company Tags: Amazon

Summary

Given an array of integers, find the total length of all non-overlapping sub-arrays such that the sum of each sub-array is equal to its length. For example, in the array [1, 2, 3, 4, 5], the non-overlapping sub-arrays with the desired property are [1], [2], [3], [4], [5]. The total length of these sub-arrays is 1 + 2 + 3 + 4 + 5 = 15.

Detailed Explanation

The problem can be solved by iterating through the array and checking for each element if it forms a valid sub-array (i.e., its sum equals its length). If such an element is found, we calculate its length and add it to our total count. We then move on to the next element in the array.

Here's a step-by-step breakdown of the solution:

  1. Initialize a variable total_length to store the total length of non-overlapping sub-arrays.
  2. Iterate through the given array from left to right.
  3. For each element, check if its sum equals its length. If yes, calculate its length and add it to total_length.
  4. Move on to the next element in the array.
  5. Repeat steps 2-4 until all elements in the array have been processed.

The time complexity of this solution is O(n), where n is the size of the input array, since we are making a single pass through the array. The space complexity is O(1) as we are not using any additional space that scales with the input size.

Optimized Solutions

Java

View on GeeksforGeeks
public int sumOfLengths(int[] arr) {
    int total_length = 0;
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == i + 1) {
            total_length += i + 1;
        }
    }
    return total_length;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.