w3resource
Java Programming Exercies

Java Exercises: Get the index of the first number and the last number of a subarray

Java Basic: Exercise-139 with Solution

Write a Java program to get the index of the first number and the last number of a subarray where the sum of numbers is zero from a given array of integers.

Pictorial Presentation:

Java Basic Exercises: Get the index of the first number and the last number of a subarray.

Sample Solution:

Java Code:

import java.util.*;
public class Solution {
    public static List<Integer> subarraySum(int[] nums) {
        List<Integer> temp = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return temp;
        }
        int pre_Sum = 0;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(pre_Sum, -1);
        for (int i = 0; i < nums.length; i++) {
            pre_Sum += nums[i];
            if (map.containsKey(pre_Sum)) {
                temp.add(map.get(pre_Sum) + 1);
                temp.add(i);
                return temp;
            }
            map.put(pre_Sum, i);
        }
        return temp;
    }
    
public static void main(String[] args) {
		int [] nums = {1, 2, 3, -6, 5, 4};
		System.out.println("Original Array : "+Arrays.toString(nums));
		System.out.println("Index of the subarray of the said array where the sum of numbers is zero: "+subarraySum(nums));
	}		
}

Sample Output:

Original Array : [1, 2, 3, -6, 5, 4]
Index of the subarray of the said array where the sum of numbers is zero: [0, 3]

Flowchart:

Flowchart: Java exercises: Get the index of the first number and the last number of a subarray.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to find all of the longest word in a given dictionary.
Next: Write a Java program to merge all overlapping Intervals from a given a collection of intervals.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming