-
Notifications
You must be signed in to change notification settings - Fork 2
/
question16.c
130 lines (105 loc) · 2.32 KB
/
question16.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
120
121
122
123
124
125
126
127
128
129
130
/*
Find the equilibrium index of an array
METHOD1:
Using two pointers i and j finding the sum from either sides and stopping when they are equal.
If right is more, incrementing left, if left is more decrementing right
Time complexity: O(n^2)
Space complexity: O(1)
METHOD2:
Take an two additional arrays. One will store the cumulative sum for left to right and other
from right to left. In a loop compare the kth with n-k remaining using these two arrays. Where the sum
is equal the value of k is the equilibrium index
Time complexity: O(n)
Space complexity: O(n)
METHOD3:
Same as method2, but instead of using two arrays, two variables are used
Time complexity: O(n)
Space complexity: O(1)
*/
//METHOD1
#include <stdio.h>
#include <stdlib.h>
int findEquilibriumIndex(int a[],int n){
int i = 0,j, sumLeft = 0, sumRight;
for(i = 0;i<n-1;i++){
sumLeft += a[i];
sumRight = 0;
for(j=i+1; j<n; j++){
sumRight += a[j];
}
if(sumLeft == sumRight){
return i;
}
}
return 0;
}
int main(){
int arr[] = {10,5,15,3,4,21,2};
int length = sizeof(arr)/sizeof(arr[0]);
int index = findEquilibriumIndex(arr, length);
if(index){
printf("equilibrium index is %d\n", index);
}else{
printf("no index found\n");
}
}
//METHOD2
#include <stdio.h>
#include <stdlib.h>
int findEquilibriumIndex(int a[],int n){
int i = 0,j;
int sumLeft[n], sumRight[n], sum = 0;
for(i=0; i<n-1; i++){
sum += a[i];
sumLeft[i] = sum;
}
sum = 0;
for(j=n-1; j>0; j--){
sum += a[j];
sumRight[j] = sum;
}
for(i=0; i<n; i++){
if(sumLeft[i] == sumRight[i+1]){
return i;
}
}
return 0;
}
int main(){
int arr[] = {10,5,15,3,4,21,2};
int length = sizeof(arr)/sizeof(arr[0]);
int index = findEquilibriumIndex(arr, length);
if(index){
printf("equilibrium index is %d\n", index);
}else{
printf("no index found\n");
}
}
//METHOD3
#include <stdio.h>
#include <stdlib.h>
int findEquilibriumIndex(int a[],int n){
int i = 0,j;
int sum = 0, sumLeft = 0;
for(i=0; i<n; i++){
sum += a[i];
}
for(j=0;j<n;j++){
sum = sum - a[j];
sumLeft += a[j];
if(sum == sumLeft){
return j;
}
}
return 0;
}
int main(){
int arr[] = {10,5,15,3,4,21,2};
int length = sizeof(arr)/sizeof(arr[0]);
int index = findEquilibriumIndex(arr, length);
if(index){
printf("equilibrium index is %d\n", index);
}else{
printf("no index found\n");
}
}