Java
Java

 

 

Program Overview

This Java program finds a contiguous subarray within a one-dimensional array of integers that sums to a specified value. It utilizes a hash map to store the cumulative sums and efficiently checks for the existence of the required sum.

Program Structure

  • Function: findSubarrayWithSum
    • Parameters: int[] array, int targetSum
    • Returns: void (prints the indices of the subarray if found)
  • Main Method
    • Tests the function with a sample array and target sum.

Java Code


import java.util.HashMap;

public class SubarraySum {
    
    /**
     * Finds a subarray with the given sum.
     * 
     * @param array The input array of integers.
     * @param targetSum The target sum to find in the subarray.
     */
    public static void findSubarrayWithSum(int[] array, int targetSum) {
        HashMap<Integer, Integer> sumMap = new HashMap<>();
        int cumulativeSum = 0;
        
        for (int i = 0; i < array.length; i++) {
            // Update cumulative sum
            cumulativeSum += array[i];
            
            // Check if cumulative sum equals the target sum
            if (cumulativeSum == targetSum) {
                System.out.println("Subarray found from index 0 to " + i);
                return;
            }
            
            // Check if there is a subarray (cumulativeSum - targetSum) in the map
            if (sumMap.containsKey(cumulativeSum - targetSum)) {
                System.out.println("Subarray found from index " + (sumMap.get(cumulativeSum - targetSum) + 1) + " to " + i);
                return;
            }
            
            // Store the cumulative sum with its index
            sumMap.put(cumulativeSum, i);
        }
        
        System.out.println("No subarray found with the given sum.");
    }

    public static void main(String[] args) {
        int[] array = {1, 2, 3, 7, 5};
        int targetSum = 12;
        findSubarrayWithSum(array, targetSum);
    }
}

Explanation of the Code

1. **Import Statements**: The program imports the HashMap class from the Java Collections Framework to facilitate storing cumulative sums.

2. **findSubarrayWithSum Method**: This method implements the core logic to find the subarray.

  • A cumulative sum variable keeps track of the sum of elements as we iterate through the array.
  • A HashMap is used to store previously seen cumulative sums along with their corresponding indices.
  • For each element, we check if the cumulative sum equals the target sum. If it does, we print the starting and ending indices.
  • We also check if the difference between the cumulative sum and the target sum exists in the map, indicating a valid subarray.

3. **Main Method**: It initializes an example array and a target sum, and calls the findSubarrayWithSum method.

Conclusion

This program efficiently finds a contiguous subarray with a specified sum using a hash map, allowing it to operate in linear time, O(n), where n is the number of elements in the input array.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)