w3resource

Java Array Exercises: Find all triplets equal to a given sum in a unsorted array of integers

Java Array: Exercise-74 with Solution

Write a Java program to find all triplets equal to a given sum in a unsorted array of integers.

Example:
Input :
nums = { 1, 6, 3, 0, 8, 4, 1, 7 }
Output:
Triplets of sum 7
(0 1 6)
(0 3 4)

Sample Solution:

Java Code:

import java.util.Arrays;

	class solution {
	
		public static void find_and_print_all_Triplets(int[] nums, int sum, int alen)
		{
		System.out.println("\nTriplets of sum "+sum);
		for (int i = 0; i <= alen - 3; i++)
			{
				int k = sum - nums[i];
				int l_index = i + 1, h_index = nums.length - 1;
	
				while (l_index < h_index)
				{
					if (nums[l_index] + nums[h_index] < k) {
						l_index++;
					}
	
				else if (nums[l_index] + nums[h_index] > k) {
						h_index--;
					}
	
					else {
						System.out.println("(" + nums[i] + " " + nums[l_index] + " " + nums[h_index] + ")");
						l_index++;
						h_index--;
					}
				}
			}
		}
		public static void main(String[] args)
		{
			int[] nums = { 1, 6, 3, 0, 8, 4, 1, 7 };
			int alen = nums.length;
			System.out.println("\nOriginal array: "+Arrays.toString(nums));
			// sort the array in ascending order
			Arrays.sort(nums);
			int sum = 7;
	
			find_and_print_all_Triplets(nums, sum, alen);
		}
	}

Sample Output:

Original array: [1, 6, 3, 0, 8, 4, 1, 7]

Triplets of sum 7
(0 1 6)
(0 3 4)

Flowchart:

Flowchart: Find all triplets equal to a given sum in a unsorted array of integers.

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to sort a given array of distinct integers where all its numbers are sorted except two numbers.
Next: Java String Exercises

What is the difficulty level of this exercise?



Java: Tips of the Day

Different between parseInt() and valueOf() in java?

Well, the API for Integer.valueOf(String) does indeed say that the String is interpreted exactly as if it were given to Integer.parseInt(String). However, valueOf(String) returns a new Integer() object whereas parseInt(String) returns a primitive int.

If you want to enjoy the potential caching benefits of Integer.valueOf(int), you could also use this eyesore:

Integer k = Integer.valueOf(Integer.parseInt("123"))

Now, if what you want is the object and not the primitive, then using valueOf(String) may be more attractive than making a new object out of parseInt(String) because the former is consistently present across Integer, Long, Double, etc.

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