Roxar Interview Question
Software Engineer InternsCountry: United States
Interview Type: Phone Interview
O(n) time, O(1) space
static int reverseSignElement(int[] array, int target) {
if (array == null || array.length == 0)
return 0;
int sum = 0;
for (int i : array) {
sum += i;
}
for (int i : array) {
if (sum - 2*i == target)
return i;
}
return 0;
}
logic derivation:
Change of sign a element in set will return the target number.
Assume R is the resultant element and we will change the sign of R
So in the sum of the all elements of set (Say Sum), R is also included. First exclude that.
So we have sum of all elements except R => Sum – R.
Now, we changed sign of R and add it to get new sum of all elements.
( Sum –R ) + ( –R) = target //we changed sign of R
i.e, Sum –R –R = target
i.e, Sum – 2*R = target
Now for which i in set, this equation will satisfy, that is the result.
Assuming all numbers in the set are positive.
- deepshikhaagrl March 17, 2016Step 1. Add the numbers in the set.
Step 2. Subtract the given sum from added total at step1.
Step 3. Divide number by 2 at step 2. Reverse the sign of this particular number.