Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Find Longest Subarray with Given Sum Using Sliding Window - Optimal Solution



Problem Statement

Given an array of positive integers and a target sum k, your task is to find the length of the longest contiguous subarray whose elements sum up to exactly k.

If no such subarray exists, return 0.

This problem assumes all elements in the array are positive, which allows us to use an efficient sliding window approach.

Examples

Input ArrayTarget Sum (k)OutputDescription
[1, 2, 3, 7, 5]122Subarray [7, 5] gives sum 12
[1, 1, 1, 1, 1, 1]33Subarray [1, 1, 1] gives sum 3, longest such subarray is of length 3
[5, 1, 2, 3, 1]62Subarray [3, 1, 2] exceeds, but [5, 1] is valid
[10, 2, 3]153Entire array sums to 15
[1, 2, 3]70No subarray sums to 7
[]50Empty array cannot have any subarray
[5]51Single-element subarray equals target
[1, 2, 3]00All elements are positive, can't reach 0 sum

Solution

To solve the problem of finding the longest subarray with a given sum k, we can take advantage of a technique called the sliding window. This approach works efficiently when all elements in the array are positive.

Understanding the Goal

We need to find a sequence of contiguous elements (a subarray) in the array that adds up exactly to k. But among all such valid subarrays, we're interested in the one with the maximum length.

Why Sliding Window Works Here

Since all numbers are positive, the sum of a subarray can only increase if we add more elements. If at any point the current sum becomes greater than k, we know we need to shrink the window from the left to try reducing the sum.

How We Approach It

  • We start with two pointers: start and end, both at index 0 initially.
  • We also maintain a curr_sum variable to store the current subarray sum, and max_len to track the maximum length found.
  • As we move the end pointer through the array:
    • We add the current element to curr_sum.
    • If curr_sum becomes greater than k, we move the start pointer right, subtracting those values from curr_sum, until it is ≤ k.
    • If curr_sum == k, we calculate the window length (end - start + 1) and update max_len if it's larger than before.

What Happens in Special Cases?

  • No matching subarray: If no window ever sums to k, max_len remains 0.
  • Empty array: There's no subarray to check, so return 0.
  • Single element equals k: Then max_len is 1.
  • Target sum is 0: Since all elements are positive, we can't reach 0, so return 0.

Conclusion

This method is optimal and runs in linear time O(n) since each element is visited at most twice (once by end, once by start). It works beautifully for arrays with only positive numbers.

Visualization

Algorithm Steps

  1. Given an array arr and a target sum k.
  2. Initialize variables: start = 0, curr_sum = 0, and max_len = 0.
  3. Traverse the array using a loop with index end:
  4. → Add arr[end] to curr_sum.
  5. → While curr_sum > k, subtract arr[start] from curr_sum and increment start.
  6. → If curr_sum == k, update max_len as max(max_len, end - start + 1).
  7. Return max_len as the result after the loop.

Code

Python
JavaScript
Java
C++
C
def longest_subarray_sum_k(arr, k):
    start = 0
    curr_sum = 0
    max_len = 0
    for end in range(len(arr)):
        curr_sum += arr[end]
        while curr_sum > k:
            curr_sum -= arr[start]
            start += 1
        if curr_sum == k:
            max_len = max(max_len, end - start + 1)
    return max_len

# Sample Input
arr = [1, 2, 3, 1, 1, 1, 1, 2]
k = 5
print("Longest Subarray Length:", longest_subarray_sum_k(arr, k))

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(n)In the best case, the subarray with the desired sum is found early without many window adjustments.
Average CaseO(n)Each element is added and removed from the window at most once, resulting in linear time complexity.
Average CaseO(n)Even if no valid subarray is found, the window expands and contracts linearly across the array.

Space Complexity

O(1)

Explanation: The algorithm uses constant extra space — only a few variables are maintained (start, end, curr_sum, max_len), regardless of input size.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M