-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathquestion20.c
119 lines (99 loc) · 2.51 KB
/
question20.c
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/*
Find the subarray with the given sum
SUBARRAY: part of the array which is contiguous and satisfied the given condition
METHOD1
Take all possible combos
Time complexity: O(n^2)
Space complexity: O(1)
METHOD2 (only for positive numbers)
Taking two pointers and scanning. Moving start index if sum is more, move end index if sum is less
Array in worst case will be traversed twice
Time complexity: O(n)
Space complexity: O(1)
METHOD3(for both negative and positive)
Maintaining a hash for sum so far and subtracting given sum each time to see if the result is present in the hash table
If present that means sub array exists which if subtracted can give a subarray which has the req sum
Time complexity: O(n)
Space complexity: O(n)
*/
//METHOD1
// #include <stdio.h>
// #include <stdlib.h>
// void printSubArray(int *arr,int start, int end){
// for(int i=start; i<=end;i++){
// printf("%d", arr[i]);
// }
// }
// int main(){
// int a[] = {5,4,6,7,9,8,3,1,2};
// int length = sizeof(a)/sizeof(a[0]);
// int start, end, sum;
// for(int i=0; i<length; i++){
// sum = 0;
// start = a[i];
// sum += start;
// for(int j=i+1; j<length; j++){
// end = a[j];
// sum += end;
// if(sum == 21){
// printSubArray(a,i,j);
// }
// }
// }
// }
//METHOD2
// #include <stdio.h>
// #include <stdlib.h>
// void printSubArray(int *arr,int start, int end){
// for(int i=start; i<=end;i++){
// printf("%d", arr[i]);
// }
// }
// int main(){
// int a[] = {5,4,6,7,9,8,3,1,2};
// int length = sizeof(a)/sizeof(a[0]);
// int reqSum = 27;
// int leftIndex = 0, rightIndex = 0, sum=0;
// if(a[leftIndex] == reqSum){
// printf("%d\n", a[leftIndex]);
// return 1;
// }else{
// rightIndex++;
// sum = a[leftIndex] + a[rightIndex];
// }
// while(rightIndex<=length){
// if(sum == reqSum){
// printSubArray(a, leftIndex, rightIndex);
// break;
// }
// if(sum < reqSum){
// rightIndex++;
// sum += a[rightIndex];
// }else{
// int temp = leftIndex;
// leftIndex++;
// sum = sum - a[temp];
// }
// }
// if(sum != reqSum){
// printf("sub array could not be found with sum given\n");
// }
// }
//METHOD3
#include <stdio.h>
#include <stdlib.h>
struct hash{
int data;
};
void findSubArray(int *a, int size, int sum){
int sumSoFar = 0;
struct hash *arr = (struct hash *)calloc(100, sizeof(struct hash));
//linear probing implementation to be done later
}
int main(){
int a[] = {8,5,-2,3,4,-5,7};
int size = sizeof(a)/sizeof(a[0]);
int reqSum = 10;
findSubArray(arr,size, reqSum);
return 0;
}