0% found this document useful (0 votes)
47 views8 pages

TASK#3:: Code For Threesum

The document discusses code for solving the 3-sum problem using two approaches - the naive approach and a faster approach. The naive approach uses three nested for loops to check all combinations, having O(n^3) time complexity. The faster approach first sorts the array and then uses two for loops and binary search, reducing the time complexity to O(n^2logn) and making it faster.

Uploaded by

Malik Naveed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views8 pages

TASK#3:: Code For Threesum

The document discusses code for solving the 3-sum problem using two approaches - the naive approach and a faster approach. The naive approach uses three nested for loops to check all combinations, having O(n^3) time complexity. The faster approach first sorts the array and then uses two for loops and binary search, reducing the time complexity to O(n^2logn) and making it faster.

Uploaded by

Malik Naveed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

TASK#3:

CODE FOR THREESUM:

package a01_daa;

/**
*
* @author
*/
public class ThreeSum {
/**
* Prints to standard output the (i, j, k) with {@code i < j < k}
* such that {@code a[i] + a[j] + a[k] == 0}.
*
* @parameter a is the array of integers
*/
public static void printAllThreeSum(int[] a) {
int n = a.length; //stored the array length in an ineteger N
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
for (int k = j+1; k < n; k++) {
if (a[i] + a[j] + a[k] == 0) {
System.out.println("Pairs are:" + a[i] + " " + a[j] + " " + a[k]); //printing pairs
of 3sum
}
}
}
}
}

/**

1
* Returns the number of triples (i, j, k) with {@code i < j < k}
* such that {@code a[i] + a[j] + a[k] == 0}.
*
* @parameter a is the array of integers
*/
public static int countSum(int[] a) {
int n = a.length; //stored array length in an integer
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
for (int k = j+1; k < n; k++) {
if (a[i] + a[j] + a[k] == 0) {
count++; //increment when found
}
}
}
}
return count; //getting number of triplets
}
}
----------------------------------------------------------------------------------------------------------------

CODE FOR FASTTHREESUM:

package a01_daa;
import java.util.*;

/**
*
* @author
*/
public class FastThreeSum {

int binarySearch(int arr[], int l, int r, int x)//method to perform binary search
{
if (r>=l) //if elemengt at right is greater or equal to left element
{
int mid = l + (r - l)/2;

// If the element is present at the middle itself


if (arr[mid] == x)
return mid;

// If element is smaller than mid, then it can only be present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l, mid-1, x);

// Else the element can only be present in right subarray


return binarySearch(arr, mid+1, r, x);
}

// when element is not present in array


return -1;
}
//function to compute FASTThreeSUM using binary search
public int FastThreeSum(int[] A) {
Arrays.sort(A); // O(nlogn) complexity
int count=0; //initialzied count to zero
for (int i = 0, l = A.length; i < l && A[i] < 0; i++) { //O(n^2 logn) complexity
for (int j = i + 1; j < l && A[i] + A[j] < 0; j++) {
int k = Arrays.binarySearch(A, j + 1, l, -A[i] - A[j]);
if (k > j) //if greater
{
count++;
//return new int[]{A[i], A[j], A[k]};
System.out.println("Pairs are:" + A[i] + " " + A[j] + " " + -(A[i] + A[j]));
}
}
}
return count; //getting the number of triplets
}

}
----------------------------------------------------------------------------------------------------------------

MAIN Function:

package a01_daa;
import java.util.*;
import java.time.*;
import java.lang.*;

/**
*
* @author
*/
public class A01_DAA {
private static int[] anArray; //initialzied an array
public static void main(String[] args) //main function
{
anArray = new int[100];
Random rand = new Random(); //Random object instantiation
for (int i = 0; i < 100; i++) {
anArray[i] = ((rand.nextInt(100)%100)-50); //generating random numbers and storing in
array
}

int[] a = anArray; //stored array elements in anther array


ThreeSum obj= new ThreeSum(); //object instantiation for THREESUM class
long start = System.currentTimeMillis( ); //starting time

int count = obj.countSum(a); //method calling and storing in an integer


long end = System.currentTimeMillis( ); //ending time

long diff = end - start; //time difference,,, giving time elapsed


obj.printAllThreeSum(a); //orinting pairs
System.out.println("Time Taken: " + diff+" Milliseconds"); //printing time for
THREESUM
System.out.println("Number of THREESUM triplets is:"+count); //orinting number of
pairs in THREESUM
FastThreeSum obj2= new FastThreeSum(); //object instantiation for FASTTHREESUM
class
long start2 = System.currentTimeMillis( ); //starting time
int count2= obj2.FastThreeSum(a); //method calling and storing in an integer
long end2 = System.currentTimeMillis( ); //ending time
long diff2 = end2 - start2; //time difference,,, giving time elapsed
System.out.println("Time Taken: " + diff2+" Milliseconds"); //orinting time for
FASTTHREESUM
System.out.println("Number of THREESUM triplets is:"+count2); //printing number of
pairs

}
}
----------------------------------------------------------------------------------------------------------------
a.
Table:
Running times for input data in seconds
1K 4K 8K 12K
3-Sum 0.485 45.851 159.392 630.527

Fast 3-Sum 0.013 0.067 0.22 0.696

Count of Triplets

3-Sum 1252881 80000470 642891274 2144516610

Fast 3-Sum 128453 2067072 8032854 18306737

b.
Graphs:

 For THREESUM:
 Fast THREESUM:

Question 2: Mention processor, RAM and OS of your

Computer? Answer:
 Processor: Intel®Core™i7-5500U CPU@ 2.40GHz (4 CPUs), ~2.4Ghz
 RAM: 8192MB
 OS: Windows 8.1 Single Language 64-bit (6.3, Build 9600)
Question 3: What makes Fast-3-sum faster than 3-sum
implementation?
Answer:
Fast THREESUM is faster than the naïve approach for THREESUM because of following
reasons:
1. Instead of checking for every possible value of K, Binary search in FAST
THREESUM helps to find the index on which A[i]+A[j] has negative value.
2. A lot of searching time is being saved in case of FAST THREESUM.
3. There are three loops in Brute-Force while two in case of FAST THREESUM.
4. The complexity for Brute-Force is O(n^3).
5. The complexity for Fast THREESUM is O(n^2log(n)).
6. The time taken to compute is greater for Cubic function as compared to Quadratic-
Logarithmic function.
7. The graph above shows the time taken for brute-force approach is almost 37-28 times.
8. The use of binary search in fast three sum makes it faster as compared to brute-force
having three for loops.

Acknowledgments:
1. https://www.geeksforgeeks.org
2. https://codereview.stackexchange.com
3. https://www.programcreek.com
4. https://github.com/

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy