How to Find Subarray with Given Sum?

A Quick Guide

Are you searching for a method to find a subarray that adds up to a specific sum? Look no further!    Let’s explore different methods to find subarrays with a given sum.

Given an array of integers, the goal is to locate a non-empty subarray that adds up to the specified sum.  Sound complicated? 

Problem Statement

Example-   Input: [11, 9, 8, 7, 13, 5, 17]  Sum: 25   Output: YES  Explanation: The subarray [7, 13, 5] adds up to 25. 

Approach 1-  Naive Approach

The naive approach involves checking every single subarray for the given sum. Are you ready to see it in action?

Time complexity: O(N^2), where N is the size of the array.  Space complexity: O(1)

Speed up your search for the perfect subarray with this approach. It involves taking an empty window and adjusting it until the given constraint is satisfied.   Ready to see how it works? Check out the algorithm!

Approach 2-  Sliding window

Click on the link below to start your journey.

Are you ready to level up your coding skills?

Step Up Your Game with InterviewBit Web Stories

Don't miss out on the chance to upskill yourself with IntervewBit's engaging web stories.