-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathSubarrayWithGivenSum.java
More file actions
74 lines (67 loc) · 1.7 KB
/
SubarrayWithGivenSum.java
File metadata and controls
74 lines (67 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*https://practice.geeksforgeeks.org/problems/subarray-with-given-sum-1587115621/1*/
/*Prateekshya's Solution*/
class Solution
{
static ArrayList<Integer> list;
static ArrayList<Integer> subarraySum(int[] arr, int n, int s)
{
list = new ArrayList<Integer>();
//create hashtable
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
int sum = 0;
map.put(0,-1);
for (int i = 0; i < n; ++i)
{
//get the sum till current point
sum += arr[i];
//check if the required sum is present somewhere
if (map.containsKey(sum-s))
{
list.add((Integer)map.get(sum-s)+2);
list.add(i+1);
return list;
}
//add to the hashtable
map.put(sum,i);
}
list.add(-1);
return list;
}
}
/*Pratik's Solution*/
class Solution
{
static ArrayList<Integer> subarraySum(int[] arr, int n, int s)
{
ArrayList<Integer> al = new ArrayList<Integer>();
int sum = arr[0];
int left=0,right=1;
while(right<n)
{
while(right<n && sum<s)
{
sum+=arr[right++];
}
if(sum==s)
{
al.add(left+1);
al.add(right);
return al;
}
while(left<right && sum>s)
{
sum-=arr[left++];
}
}
if(sum==s)
{
al.add(left+1);
al.add(right);
}
else
{
al.add(-1);
}
return al;
}
}