Subarray Sum

LintCode-138.Subarray Sum

Given an integer array, find a subarray where the sum of numbers is zero. Your code should return the index of the first number and the index of the last number.

Notice: There is at least one subarray that it's sum equals to zero.

Have you met this question in a real interview? Yes
Example: Given [-3, 1, 2, -3, 4], return [0, 2] or [1, 3].

public class Solution {
    /**
     * @param nums: A list of integers
     * @return: A list of integers includes the index of the first number 
     *          and the index of the last number
     */
    public ArrayList<Integer> subarraySum(int[] nums) {
        ArrayList<Integer> result = new ArrayList<>();
        
        if (nums == null || nums.length == 0) {
            return result;
        }
        
        int sum = 0;
        HashMap<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            
            if (sum == 0) {
                result.add(0);
                result.add(i);
                break;
            }
            
            if (map.containsKey(sum)) {
                result.add(map.get(sum) + 1);
                result.add(i);
                break;
            }
            
            map.put(sum, i);
        }
        
        return result;
    }
}

Hope this helps,
Michael

DigitalOcean Referral Badge