﻿ Java exercises: Get the index of the first number and the last number of a subarray - w3resource # 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: 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)) {
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: Java Code Editor:

What is the difficulty level of this exercise?

﻿

## Java: Tips of the Day

initial:

Returns all the elements of an array except the last one. Use Arrays.copyOfRange() to return all except the last one

```public static <T> T[] initial(T[] elements) {
return Arrays.copyOfRange(elements, 0, elements.length - 1);
}
```

Ref: https://bit.ly/3zEKw9u