Premise
It is hard to analyze this without any additional input how nums
and target
correspond to each other.
Since you do not provide any additional information here, I have to assume that all inputs are possible. In which case the worst case is that none of the pairs buildable by nums
can form target
at all.
A simple example explaining what I am referring to would be target = 2
with nums = [4, 5, 10, 3, 9]
. You can not build target
by adding up pairs of nums
.
Iterations
So you would end up never hitting your break
statement, going through the full execution of the algorithm.
That is, the full range of k
from 0
to nums.length - 1
, then one increment of i
and then k
again the full range, starting from i
. And so on until i
reaches the end as well.
In total, you will thus have the following amount of iterations (where n
denotes nums.length
):
n, n - 1, n - 2, n - 3, ..., 2, 1
Summed up, those are exactly
(n^2 + n) / 2
iterations.
Complexity
Since all you do inside the iterations is in constant time O(1)
, the Big-O complexity of your algorithm is given by
(n^2 + n) / 2 <= n^2 + n <= n^2 + n^2 <= 2n^2
Which by definition is in O(n^2)
.
Alternative code
Your code is very hard to read and a rather unusual way to express what you are doing here (namely forming all pairs, leaving out duplicates). I would suggest rewriting your code like that:
for (int i = 0; i < nums.length; i++) {
for (int j = i; j < nums.length; j++) {
int first = nums[i];
int second = nums[j];
if (first + second == target) {
return {i, j};
}
}
}
return null;
Also, do yourself a favor and do not return result
filled with 0
in case you did not find any hit. Either return null
as shown or use Optional
, for example:
return Optional.of(...);
...
return Optional.empty();