r/CodingProblems • u/krishnan_navadia • Feb 11 '20
Day 1 [2020-02-11]: Problem of the day [Asked by Twitter]
Given an array, nums , of n integers, find all unique triplets (three numbers, a, b, & c) in nums such that a + b + c = 0. Note that there may not be any triplets that sum to
zero in nums , and that the triplets must not be duplicates.
Input:
[0, -1, 2, -3, 1]
Output:
[0, -1, 1], [2, -3, 1]
2
Upvotes
0
May 31 '20
[deleted]
1
u/LinkifyBot May 31 '20
I found links in your comment that were not hyperlinked:
I did the honors for you.
delete | information | <3
1
u/forestplay May 31 '20
My solution in java, open to suggestions:
import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);String strOfNumbers = scanner.nextLine().replaceAll("[\\[\\],]", "");int[] input = Arrays.stream(strOfNumbers.split(" ")).mapToInt(Integer::parseInt).toArray();ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();for (int i = 0; i < input.length - 2; i++)for (int j = i + 1; j < input.length - 1; j++)for (int k = j + 1; k < input.length; k++)if (input[i] + input[j] + input[k] == 0)results.add(new ArrayList<Integer>(List.of(input[i], input[j], input[k])));System.out.println(results.toString().replaceAll("^.", "").replaceAll(".$", ""));}}