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)) {
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:
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?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework