filmov
tv
Array - 26: Find Sub-array whose sum is equal to given sum

Показать описание
Solution - 1: When you've all positive numbers
- We take two variable start & end which're pointing to starting element
- We take another variable window_sum = 0
- Now start from 1st element & add into window_sum
- If window_sum == given_sum, then we've got our sybarray
- If window_sum is less than given-sum then keep on adding element
- If window_sum is greater than given-sum then we decrease the element from the starting
- whenever you window_sum == sum, print start & end index
Time Complexity: O(n)
Space Complexity: O(1)
Solution - 2: For any case
- We take variable end which're pointing to starting element
- We take another variable total_sum_till_here = 0 & a map where key'll store total_sum_till_here & value will be index where this sum is present
- Now start from 1st element & if total_sum_till_here == given-sum, you've got sub-array, print the start & end index
- If total_sum_till_here - given_sum is present in map, it means value exists, so subarray will from start+1 to end
- If total_sum_till_here - given_sum is not present, then you total_sum_till_here as map key
Time Complexity: O(n)
Space Complexity: O(n)
Do Watch video for more info
CHECK OUT CODING SIMPLIFIED
★☆★ VIEW THE BLOG POST: ★☆★
I started my YouTube channel, Coding Simplified, during Dec of 2015.
Since then, I've published over 400+ videos.
★☆★ SUBSCRIBE TO ME ON YOUTUBE: ★☆★
★☆★ Send us mail at: ★☆★
- We take two variable start & end which're pointing to starting element
- We take another variable window_sum = 0
- Now start from 1st element & add into window_sum
- If window_sum == given_sum, then we've got our sybarray
- If window_sum is less than given-sum then keep on adding element
- If window_sum is greater than given-sum then we decrease the element from the starting
- whenever you window_sum == sum, print start & end index
Time Complexity: O(n)
Space Complexity: O(1)
Solution - 2: For any case
- We take variable end which're pointing to starting element
- We take another variable total_sum_till_here = 0 & a map where key'll store total_sum_till_here & value will be index where this sum is present
- Now start from 1st element & if total_sum_till_here == given-sum, you've got sub-array, print the start & end index
- If total_sum_till_here - given_sum is present in map, it means value exists, so subarray will from start+1 to end
- If total_sum_till_here - given_sum is not present, then you total_sum_till_here as map key
Time Complexity: O(n)
Space Complexity: O(n)
Do Watch video for more info
CHECK OUT CODING SIMPLIFIED
★☆★ VIEW THE BLOG POST: ★☆★
I started my YouTube channel, Coding Simplified, during Dec of 2015.
Since then, I've published over 400+ videos.
★☆★ SUBSCRIBE TO ME ON YOUTUBE: ★☆★
★☆★ Send us mail at: ★☆★
Комментарии