Skip to content
Advertisement

Two sum return statement returns nothing

I’m trying to attempt a problem where I must add two elements in an array to equal a target integer value. I think my code is correct and will return the desired target however the return statement is not returning any value. why is this and how can I fix it?

Thanks

public static void main(String[] args) {
    int[] nums= {2,7,11,15};
    int target= 9;
    
}
    public int twoSum(int[] nums, int target) {
        int result=0; 
        for(int i = 0; i<nums.length ;i++){
            for(int j=i+1; j<nums.length ;j++ ){
                result = nums[i] + nums[j];
                if (result == target){
                  return result;
                }else{
                    break;
                }
            }
        }
    
        
        
    }
}

Advertisement

Answer

break is wrongly used. Also, you have to return result. I’m not sure if this code compiles. Is it? You have to call method twoSum(...), too. I see that your array is sorted, which means you can actually solve the problem in O(n) time by using two pointers: left and right, like follows:

import java.util.Arrays;

class Solution {
    
    // O(n) time, O(1) space
    private static boolean twoNumberSum(int[] array, int sum) {
        if (array.length < 2) {
            return false;
        }
        int left_idx = 0;
        int right_idx = array.length - 1;
        
        // O(n) time, O(1) space
        while (left_idx < right_idx) {
            int currentSum = array[left_idx] + array[right_idx]; 
            if (currentSum < sum) {
                left_idx++;
            }
            else if (currentSum > sum) {
                right_idx--;
            }
            else {
                return true;
            }
        }
        return false;
    }

    public static void main(String ...args) {
        int[] array = {2, 7, 11, 15};
        int valid_sum = 9;
        int invalid_sum = 10;
        
        System.out.format("(%s, %d) -> %bn", Arrays.toString(array), valid_sum, Solution.twoNumberSum(array, valid_sum));
        System.out.format("(%s, %d) -> %bn", Arrays.toString(array), invalid_sum, Solution.twoNumberSum(array, invalid_sum));
    }
}

Another solution, useful for unsorted arrays, would be to use a hashset -> O(n) time, O(n) space.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement