How can you improve the space and time complexity Big(0) of when nested loops are needed?

Viewed 158

The objective is to create a function that accepts two arguments: and array of integers and an integer that is our target, the function should return the two indexes of the array elements that add up to the target. We cannot sum and element by it self and we should assume that the given array always contains and answer

I solved this code kata exercise using a a for loop and a while loop. The time complexity for a for loop when N is the total elements of the array is linear O(N) but for each element there is a while process hat also increases linearly.

Does this means that the total time complexity of this code is O(N²) ?


public int[] twoSum(int[] nums, int target) {
        int[] answer = new int[2];
        for (int i = 0; i <= nums.length - 1; i++){
            int finder = 0;
            int index = 0;
            while ( index <= nums.length - 1 ){
                if (nums[i] != nums[index]){
                    finder = nums[i] + nums[index];
                        if (finder == target){
                            answer[0] = index;
                            answer[1] = i;
                        }
                }
             index++;   
            }
            
        }
        return answer;
        
    }

How would you optimize this for time and space complexity?

1 Answers

Does this means that the total time complexity of this code is O(N²) ?

Yes, your reasoning is correct and your code is indeed O(N²) time complexity.

How would you optimize this for time and space complexity?

You can use an auxilary data structure, or sort the array, and perform lookups on the array.

One simple solution, which is O(n) average case is using a hash table, and inserting elements while you traverse the list. Then, you need to lookup for target - x in your hash table, assuming the element currently traversed is x.

I am leaving the implementation to you, I am sure you can do it and learn a lot in the process!

Related