Skip to main content

Find if there is a subarray with 0 sum

Here given code implementation process.

/*
  Java program
  Find if there is a subarray with 0 sum
*/
import java.util.Set;
import java.util.HashSet;

public class SubArraySum
{
    // This function are displaying given array elements
    public void display(int[] arr, int size)
    {
        for (int i = 0; i < size; ++i)
        {
            System.out.print(" " + arr[i]);
        }
        System.out.print("\n");
    }
    // Check whether given array contains zero sum subarray or not
    public void zeroSumSubarray(int[] arr,int n)
    {
        // Display given array elements
        System.out.print("\n  Array :");
        display(arr, n);
        // Use for get unique elements
        Set<Integer> result = new HashSet <Integer> ();
        // Result indicator
        boolean status = false;
        // Use that to add array elements
        int sum = 0;
        int i = 0;
        // Execute loop through by size of array elements
        for (i = 0; i < n && status == false; ++i)
        {
            // Calculate sum of array elements
            sum += arr[i];
          
            if (sum == 0 || arr[i] == 0 || result.contains(sum))
            {
                // When zero sum subarray exists
                status = true;
            }
            else
            {
                // Add the current sum
                result.add(sum);
            }
        }
        if (status == true)
        {
            // When subarray of zero sum exists
            System.out.print("  Zero sum subarray exists  \n");
        }
        else
        {
            // When subarray of zero sum are not exists
            System.out.print("  Zero sum subarrays are not exists \n");
        }
    }
    public static void main(String[] args)
    {
        SubArraySum task = new SubArraySum();
        // Case 1
        // Define the array elements
        int[] arr1 = {
            1 , 3 , 3 , 4 , -5 , -2 , 3 , 4
        };
        int n = arr1.length;
        task.zeroSumSubarray(arr1, n);
        // Case 2
        // Define the array elements
        int []arr2 = {
            1 , 2 , 3 , -4
        };
        n = arr2.length;
        task.zeroSumSubarray(arr2, n);
    }
}

Output

  Array : 1 3 3 4 -5 -2 3 4
  Zero sum subarray exists

  Array : 1 2 3 -4
  Zero sum subarrays are not exists
// Include header file
#include <iostream>

#include <set>

using namespace std;
class SubArraySum
{
	public:
		// This function are displaying given array elements
		void display(int arr[], int size)
		{
			for (int i = 0; i < size; ++i)
			{
				cout << " " << arr[i];
			}
			cout << "\n";
		}
	// Check whether given array contains zero sum subarray or not
	void zeroSumSubarray(int arr[], int n)
	{
		// Display given array elements
		cout << "\n  Array :";
		this->display(arr, n);
		// Use for get unique elements
		set <int> result;
		// Result indicator
		bool status = false;
		// Use that to add array elements
		int sum = 0;
		int i = 0;
		// Execute loop through by size of array elements
		for (i = 0; i < n && status == false; ++i)
		{
			// Calculate sum of array elements
			sum += arr[i];
			if (sum == 0 || arr[i] == 0 || result.find(sum) != result.end())
			{
				// When zero sum subarray exists
				status = true;
			}
			else
			{
				result.insert(sum);
			}
		}
		if (status == true)
		{
			// When subarray of zero sum exists
			cout << "  Zero sum subarray exists  \n";
		}
		else
		{
			// When subarray of zero sum are not exists
			cout << "  Zero sum subarrays are not exists \n";
		}
	}
};
int main()
{
	SubArraySum task = SubArraySum();
	// Case 1
	// Define the array elements
	int arr1[] = {
		1 , 3 , 3 , 4 , -5 , -2 , 3 , 4
	};
	int n = sizeof(arr1) / sizeof(arr1[0]);
	task.zeroSumSubarray(arr1, n);
	// Case 2
	// Define the array elements
	int arr2[] = {
		1 , 2 , 3 , -4
	};
	n = sizeof(arr2) / sizeof(arr2[0]);
	task.zeroSumSubarray(arr2, n);
	return 0;
}

Output

  Array : 1 3 3 4 -5 -2 3 4
  Zero sum subarray exists

  Array : 1 2 3 -4
  Zero sum subarrays are not exists
// Include namespace system
using System;
using System.Collections.Generic;
public class SubArraySum
{
	// This function are displaying given array elements
	public void display(int[] arr, int size)
	{
		for (int i = 0; i < size; ++i)
		{
			Console.Write(" " + arr[i]);
		}
		Console.Write("\n");
	}
	// Check whether given array contains zero sum subarray or not
	public void zeroSumSubarray(int[] arr, int n)
	{
		// Display given array elements
		Console.Write("\n  Array :");
		display(arr, n);
		// Use for get unique elements
		HashSet <int> result = new HashSet < int > ();
		// Result indicator
		Boolean status = false;
		// Use that to add array elements
		int sum = 0;
		int i = 0;
		// Execute loop through by size of array elements
		for (i = 0; i < n && status == false; ++i)
		{
			// Calculate sum of array elements
			sum += arr[i];
			if (sum == 0 || arr[i] == 0 || result.Contains(sum))
			{
				// When zero sum subarray exists
				status = true;
			}
			else
			{
				result.Add(sum);
			}
		}
		if (status == true)
		{
			// When subarray of zero sum exists
			Console.Write("  Zero sum subarray exists  \n");
		}
		else
		{
			// When subarray of zero sum are not exists
			Console.Write("  Zero sum subarrays are not exists \n");
		}
	}
	public static void Main(String[] args)
	{
		SubArraySum task = new SubArraySum();
		// Case 1
		// Define the array elements
		int[] arr1 = {
			1 , 3 , 3 , 4 , -5 , -2 , 3 , 4
		};
		int n = arr1.Length;
		task.zeroSumSubarray(arr1, n);
		// Case 2
		// Define the array elements
		int[] arr2 = {
			1 , 2 , 3 , -4
		};
		n = arr2.Length;
		task.zeroSumSubarray(arr2, n);
	}
}

Output

  Array : 1 3 3 4 -5 -2 3 4
  Zero sum subarray exists

  Array : 1 2 3 -4
  Zero sum subarrays are not exists
<?php
/*
  Php program
  Find if there is a subarray with 0 sum
*/
class SubArraySum
{
	// This function are displaying given array elements
	public	function display( & $arr, $size)
	{
		for ($i = 0; $i < $size; ++$i)
		{
			echo " ". $arr[$i];
		}
		echo "\n";
	}
	// Check whether given array contains zero sum subarray or not
	public	function zeroSumSubarray( & $arr, $n)
	{
		// Display given array elements
		echo "\n  Array :";
		$this->display($arr, $n);
		// Use for get unique elements
		$result = array();
		// Result indicator
		$status = false;
		// Use that to add array elements
		$sum = 0;
		$i = 0;
		// Execute loop through by size of array elements
		for ($i = 0; $i < $n && $status == false; ++$i)
		{
			// Calculate sum of array elements
			$sum += $arr[$i];
			if ($sum == 0 || $arr[$i] == 0 || (array_search($sum, $result) !== false))
			{
				// When zero sum subarray exists
				$status = true;
			}
			else
			{
				$result[] = $sum;
			}
		}
		if ($status == true)
		{
			// When subarray of zero sum exists
			echo "  Zero sum subarray exists  \n";
		}
		else
		{
			// When subarray of zero sum are not exists
			echo "  Zero sum subarrays are not exists \n";
		}
	}
}

function main()
{
	$task = new SubArraySum();
	// Case 1
	// Define the array elements
	$arr1 = array(1, 3, 3, 4, -5, -2, 3, 4);
	$n = count($arr1);
	$task->zeroSumSubarray($arr1, $n);
	// Case 2
	// Define the array elements
	$arr2 = array(1, 2, 3, -4);
	$n = count($arr2);
	$task->zeroSumSubarray($arr2, $n);
}
main();

Output

  Array : 1 3 3 4 -5 -2 3 4
  Zero sum subarray exists

  Array : 1 2 3 -4
  Zero sum subarrays are not exists
/*
  Node Js program
  Find if there is a subarray with 0 sum
*/
class SubArraySum
{
	// This function are displaying given array elements
	display(arr, size)
	{
		for (var i = 0; i < size; ++i)
		{
			process.stdout.write(" " + arr[i]);
		}
		process.stdout.write("\n");
	}
	// Check whether given array contains zero sum subarray or not
	zeroSumSubarray(arr, n)
	{
		// Display given array elements
		process.stdout.write("\n  Array :");
		this.display(arr, n);
		// Use for get unique elements
		var result = new Set();
		// Result indicator
		var status = false;
		// Use that to add array elements
		var sum = 0;
		var i = 0;
		// Execute loop through by size of array elements
		for (i = 0; i < n && status == false; ++i)
		{
			// Calculate sum of array elements
			sum += arr[i];
			if (sum == 0 || arr[i] == 0 || result.has(sum))
			{
				// When zero sum subarray exists
				status = true;
			}
			else
			{
				result.add(sum);
			}
		}
		if (status == true)
		{
			// When subarray of zero sum exists
			process.stdout.write("  Zero sum subarray exists  \n");
		}
		else
		{
			// When subarray of zero sum are not exists
			process.stdout.write("  Zero sum subarrays are not exists \n");
		}
	}
}

function main()
{
	var task = new SubArraySum();
	// Case 1
	// Define the array elements
	var arr1 = [1, 3, 3, 4, -5, -2, 3, 4];
	var n = arr1.length;
	task.zeroSumSubarray(arr1, n);
	// Case 2
	// Define the array elements
	var arr2 = [1, 2, 3, -4];
	n = arr2.length;
	task.zeroSumSubarray(arr2, n);
}
main();

Output

  Array : 1 3 3 4 -5 -2 3 4
  Zero sum subarray exists

  Array : 1 2 3 -4
  Zero sum subarrays are not exists
#   Python 3 program
#   Find if there is a subarray with 0 sum

class SubArraySum :
	#  This function are displaying given list elements
	def display(self, arr, size) :
		i = 0
		while (i < size) :
			print(" ", arr[i], end = "")
			i += 1
		
		print(end = "\n")
	
	#  Check whether given list contains zero sum sublist or not
	def zeroSumSubarray(self, arr, n) :
		#  Display given list elements
		print("\n  Array :", end = "")
		self.display(arr, n)
		#  Use for get unique elements
		result = set()
		#  Result indicator
		status = False
		#  Use that to add list elements
		sum = 0
		i = 0
		#  Execute loop through by size of list elements
		while (i < n and status == False) :
			#  Calculate sum of list elements
			sum += arr[i]
			if (sum == 0 or arr[i] == 0 or sum in result) :
				#  When zero sum sublist exists
				status = True
			else :
				#  Add the current sum
				result.add(sum)
			
			i += 1
		
		if (status == True) :
			#  When sublist of zero sum exists
			print("  Zero sum subarray exists  ")
		else :
			#  When sublist of zero sum are not exists
			print("  Zero sum subarrays are not exists ")
		
	

def main() :
	task = SubArraySum()
	#  Case 1
	#  Define the list elements
	arr1 = [1, 3, 3, 4, -5, -2, 3, 4]
	n = len(arr1)
	task.zeroSumSubarray(arr1, n)
	#  Case 2
	#  Define the list elements
	arr2 = [1, 2, 3, -4]
	n = len(arr2)
	task.zeroSumSubarray(arr2, n)

if __name__ == "__main__": main()

Output

  Array :  1  3  3  4  -5  -2  3  4
  Zero sum subarray exists

  Array :  1  2  3  -4
  Zero sum subarrays are not exists
#   Ruby program
#   Find if there is a subarray with 0 sum

class SubArraySum 
	#  This function are displaying given array elements
	def display(arr, size) 
		i = 0
		while (i < size) 
			print(" ", arr[i])
			i += 1
		end
		print("\n")
	end

	#  Check whether given array contains zero sum subarray or not
	def zeroSumSubarray(arr, n) 
		#  Display given array elements
		print("\n  Array :")
		self.display(arr, n)
		#  Use for get unique elements
		result = []
		#  Result indicator
		status = false
		#  Use that to add array elements
		sum = 0
		i = 0
		#  Execute loop through by size of array elements
		while (i < n && status == false) 
			#  Calculate sum of array elements
			sum += arr[i]
			if (sum == 0 || arr[i] == 0 || result.include?(sum)) 
				#  When zero sum subarray exists
				status = true
			else 
				result.push(sum)
			end

			i += 1
		end

		if (status == true) 
			#  When subarray of zero sum exists
			print("  Zero sum subarray exists  \n")
		else 
			#  When subarray of zero sum are not exists
			print("  Zero sum subarrays are not exists \n")
		end

	end

end

def main() 
	task = SubArraySum.new()
	#  Case 1
	#  Define the array elements
	arr1 = [1, 3, 3, 4, -5, -2, 3, 4]
	n = arr1.length
	task.zeroSumSubarray(arr1, n)
	#  Case 2
	#  Define the array elements
	arr2 = [1, 2, 3, -4]
	n = arr2.length
	task.zeroSumSubarray(arr2, n)
end

main()

Output

  Array : 1 3 3 4 -5 -2 3 4
  Zero sum subarray exists  

  Array : 1 2 3 -4
  Zero sum subarrays are not exists 
import scala.collection.mutable._;
/*
  Scala program
  Find if there is a subarray with 0 sum
*/
class SubArraySum
{
	// This function are displaying given array elements
	def display(arr: Array[Int], size: Int): Unit = {
		var i: Int = 0;
		while (i < size)
		{
			print(" " + arr(i));
			i += 1;
		}
		print("\n");
	}
	// Check whether given array contains zero sum subarray or not
	def zeroSumSubarray(arr: Array[Int], n: Int): Unit = {
		// Display given array elements
		print("\n  Array :");
		this.display(arr, n);
		// Use for get unique elements
		var result: Set[Int] = Set();
		// Result indicator
		var status: Boolean = false;
		// Use that to add array elements
		var sum: Int = 0;
		var i: Int = 0;
		// Execute loop through by size of array elements
		while (i < n && status == false)
		{
			// Calculate sum of array elements
			sum += arr(i);
			if (sum == 0 || arr(i) == 0 || result.contains(sum))
			{
				// When zero sum subarray exists
				status = true;
			}
			else
			{
				result.add(sum);
			}
			i += 1;
		}
		if (status == true)
		{
			// When subarray of zero sum exists
			print("  Zero sum subarray exists  \n");
		}
		else
		{
			// When subarray of zero sum are not exists
			print("  Zero sum subarrays are not exists \n");
		}
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var task: SubArraySum = new SubArraySum();
		// Case 1
		// Define the array elements
		var arr1: Array[Int] = Array(1, 3, 3, 4, -5, -2, 3, 4);
		var n: Int = arr1.length;
		task.zeroSumSubarray(arr1, n);
		// Case 2
		// Define the array elements
		var arr2: Array[Int] = Array(1, 2, 3, -4);
		n = arr2.length;
		task.zeroSumSubarray(arr2, n);
	}
}

Output

  Array : 1 3 3 4 -5 -2 3 4
  Zero sum subarray exists

  Array : 1 2 3 -4
  Zero sum subarrays are not exists
/*
  Swift 4 program
  Find if there is a subarray with 0 sum
*/
class SubArraySum
{
	// This function are displaying given array elements
	func display(_ arr: [Int], _ size: Int)
	{
		var i: Int = 0;
		while (i < size)
		{
			print(" ", arr[i], terminator: "");
			i += 1;
		}
		print(terminator: "\n");
	}
	// Check whether given array contains zero sum subarray or not
	func zeroSumSubarray(_ arr: [Int], _ n: Int)
	{
		// Display given array elements
		print("\n  Array :", terminator: "");
		self.display(arr, n);
		// Use for get unique elements
		var result = Set<Int>()
		// Result indicator
		var status: Bool = false;
		// Use that to add array elements
		var sum: Int = 0;
		var i: Int = 0;
		// Execute loop through by size of array elements
		while (i < n && status == false)
		{
			// Calculate sum of array elements
			sum += arr[i];
			if (sum == 0 || arr[i] == 0 || result.contains(sum))
			{
				// When zero sum subarray exists
				status = true;
			}
			else
			{
				result.insert(sum);
			}
			i += 1;
		}
		if (status == true)
		{
			// When subarray of zero sum exists
			print("  Zero sum subarray exists  ");
		}
		else
		{
			// When subarray of zero sum are not exists
			print("  Zero sum subarrays are not exists ");
		}
	}
}
func main()
{
	let task: SubArraySum = SubArraySum();
	// Case 1
	// Define the array elements
	let arr1: [Int] = [1, 3, 3, 4, -5, -2, 3, 4];
	var n: Int = arr1.count;
	task.zeroSumSubarray(arr1, n);
	// Case 2
	// Define the array elements
	let arr2: [Int] = [1, 2, 3, -4];
	n = arr2.count;
	task.zeroSumSubarray(arr2, n);
}
main();

Output

  Array :  1  3  3  4  -5  -2  3  4
  Zero sum subarray exists

  Array :  1  2  3  -4
  Zero sum subarrays are not exists
/*
  Kotlin program
  Find if there is a subarray with 0 sum
*/
class SubArraySum
{
	// This function are displaying given array elements
	fun display(arr: Array <Int> , size: Int): Unit
	{
		var i: Int = 0;
		while (i < size)
		{
			print(" " + arr[i]);
			i += 1;
		}
		print("\n");
	}
	// Check whether given array contains zero sum subarray or not
	fun zeroSumSubarray(arr: Array < Int > , n: Int): Unit
	{
		// Display given array elements
		print("\n  Array :");
		this.display(arr, n);
		// Use for get unique elements
		var result = mutableSetOf <Int> ();
		// Result indicator
		var status: Boolean = false;
		// Use that to add array elements
		var sum: Int = 0;
		var i: Int = 0;
		// Execute loop through by size of array elements
		while (i < n && status == false)
		{
			// Calculate sum of array elements
			sum += arr[i];
			if (sum == 0 || arr[i] == 0 || result.contains(sum))
			{
				// When zero sum subarray exists
				status = true;
			}
			else
			{
				result.add(sum);
			}
			i += 1;
		}
		if (status == true)
		{
			// When subarray of zero sum exists
			print("  Zero sum subarray exists  \n");
		}
		else
		{
			// When subarray of zero sum are not exists
			print("  Zero sum subarrays are not exists \n");
		}
	}
}
fun main(args: Array <String> ): Unit
{
	var task: SubArraySum = SubArraySum();
	// Case 1
	// Define the array elements
	var arr1: Array <Int> = arrayOf(1, 3, 3, 4, -5, -2, 3, 4);
	var n: Int = arr1.count();
	task.zeroSumSubarray(arr1, n);
	// Case 2
	// Define the array elements
	var arr2: Array < Int > = arrayOf(1, 2, 3, -4);
	n = arr2.count();
	task.zeroSumSubarray(arr2, n);
}

Output

  Array : 1 3 3 4 -5 -2 3 4
  Zero sum subarray exists

  Array : 1 2 3 -4
  Zero sum subarrays are not exists




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment