algorithm - What is the right way to solve Codility's PermMissingElem test? (Java) -
i have following problem taken codility's code testing exercises:
a zero-indexed array consisting of n different integers given. array contains integers in range [1..(n + 1)], means 1 element missing.
your goal find missing element.
write function:
class solution { public int solution(int[] a); }
that, given zero-indexed array a, returns value of missing element.
for example, given array such that:
a[0] = 2 a[1] = 3 a[2] = 1 a[3] = 5
the function should return 4, missing element.
assume that:
n integer within range [0..100,000]; elements of distinct; each element of array integer within range [1..(n + 1)].
complexity:
expected worst-case time complexity o(n); expected worst-case space complexity o(1), beyond input storage (not >counting storage required input arguments).
elements of input arrays can modified.
my approach convert given array arraylist, use arraylist find lowest , highest values inside array, , iterate through possible values lowest highest, , return missing value.
this solves example problem, problem seems cannot right answers under following conditions of given array:
"empty list , single element"
"the first or last element missing"
"single element"
"two elements"
what doing wrong, , proper way go solving problem?
this problem has mathematical solution, based on fact sum of consecutive integers 1 n equal n(n+1)/2
.
using formula can calculate sum 1 n+1
. o(n)
time complexity calculate actual sum of elements in array.
the difference between full , actual totals yield value of missing element.
space complexity o(1)
.
Comments
Post a Comment