Java Online Compiler
Example: Triplets with Given Sum - Brute Force in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Triplets with Given Sum - Brute Force import java.util.ArrayList; import java.util.Arrays; import java.util.List; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { int[] arr = {12, 3, 1, 2, -6, 5, -8, 6}; int targetSum = 0; List<List<Integer>> result = findTripletsBruteForce(arr, targetSum); System.out.println("Triplets (Brute Force) for sum " + targetSum + ":"); result.forEach(System.out::println); int[] arr2 = {1, 2, 3, 4, 5, 6}; targetSum = 9; List<List<Integer>> result2 = findTripletsBruteForce(arr2, targetSum); System.out.println("\nTriplets (Brute Force) for sum " + targetSum + ":"); result2.forEach(System.out::println); } public static List<List<Integer>> findTripletsBruteForce(int[] arr, int targetSum) { List<List<Integer>> triplets = new ArrayList<>(); int n = arr.length; // Sort the array to handle duplicates later (optional for correctness but good for unique triplets) // Although sorting itself is O(N log N), the O(N^3) dominates. Arrays.sort(arr); // Step 1: Iterate through the first element for (int i = 0; i < n - 2; i++) { // Skip duplicate elements for the first number if (i > 0 && arr[i] == arr[i - 1]) { continue; } // Step 2: Iterate through the second element for (int j = i + 1; j < n - 1; j++) { // Skip duplicate elements for the second number if (j > i + 1 && arr[j] == arr[j - 1]) { continue; } // Step 3: Iterate through the third element for (int k = j + 1; k < n; k++) { // Skip duplicate elements for the third number if (k > j + 1 && arr[k] == arr[k - 1]) { continue; } // Step 4: Check if the sum equals the target if (arr[i] + arr[j] + arr[k] == targetSum) { triplets.add(Arrays.asList(arr[i], arr[j], arr[k])); } } } } return triplets; } }
Output
Clear
ADVERTISEMENTS