Member-only story

Sub-array with Given Sum:

Paresh Krishna Sharma
3 min readJul 13, 2023

--

Efficient Approach to Find a Solution

Example of sub-array

Subarray with Given Sum problem involves finding a contiguous subarray within a given array that has a specific target sum. This problem has various applications in computer science, such as financial analysis, data analytics, and signal processing. In this article, we will explore efficient algorithms to solve this problem, analyze their time and space complexities, and provide code examples for better understanding.

Naive Approach

A naive approach to solve this problem would involve checking all possible sub-arrays and comparing their sums with the given target sum. We can achieve this by using nested loops. However, this approach has a time complexity of O(n²), making it inefficient for large input arrays.

Efficient Approach

Using the Two Pointer Technique to improve the time complexity, we can use the two pointer technique, also known as the sliding window technique. This approach requires maintaining two pointers, “start” and “end,” which represent the boundaries of the current sub-array.

Two pointer approach

Algorithm

--

--

Paresh Krishna Sharma
Paresh Krishna Sharma

Written by Paresh Krishna Sharma

Unleashing the Power of Code, Data, and Creativity ✨ | Software Engineer at Microsoft | LinkedIn : www.linkedin.com/in/itsparesh

No responses yet