C# || 3Sum – How To Get All Triplet Combinations In Array Equal To Target Value Using C#
The following is a module with functions which demonstrates how to get all triplet combinations in an array equal to a target value using C#.
1. 3 Sum – Problem Statement
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Example 2:
Input: nums = []
Output: []
Example 3:
Input: nums = [0]
Output: []
2. 3 Sum – Solution
The following is a solution which demonstrates how to get all triplet combinations in an array equal to a target value.
This solution uses the two pointer technique to find combinations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
// ============================================================================ // Author: Kenneth Perkins // Date: Oct 28, 2021 // Taken From: http://programmingnotes.org/ // File: Solution.cs // Description: Demonstrates how to get 3 numbers equal to target value // ============================================================================ public class Solution { public IList<IList<int>> ThreeSum(int[] nums) { var result = new List<IList<int>>(); // Sort the array Array.Sort(nums); // Set the target value var target = 0; // Loop through numbers for (int index = 0; index < nums.Length; ++index) { // Skip duplicates if (index > 0 && nums[index] == nums[index - 1]) { continue; } // Find all 3 sum combinations that equal the target value var startIndex = index + 1; var endIndex = nums.Length - 1; while (startIndex < endIndex) { // Get the sum var sum = nums[index] + nums[startIndex] + nums[endIndex]; // Sum equals target if (sum == target) { // Add values to results when a target is found var valueStart = nums[startIndex]; var valueEnd = nums[endIndex]; result.Add(new List<int>{nums[index], valueStart, valueEnd}); // Advance past duplicate items to the 'next' values // at the start and end of the array while (startIndex < endIndex && valueStart == nums[startIndex]) { ++startIndex; } while (startIndex < endIndex && valueEnd == nums[endIndex]) { --endIndex; } // Sum is less than target } else if (sum < target) { ++startIndex; // Sum is greater than target } else { --endIndex; } } } return result; } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output for the example cases:
[[-1,-1,2],[-1,0,1]]
[]
[]
Leave a Reply