Question

In: Computer Science

Topic is Big O Problem 5 Invent a faster solution to the ThreeSum problem. Then determine...

Topic is Big O

Problem 5

Invent a faster solution to the ThreeSum problem. Then determine the number of triples of integers that sum to zero in 8ints.txt.

Hint 1:Sort the array first (use Java’s built-inArrays.sort(int[] a))method to sort the array first.

Hint 2:A pair a[i] and a[j] is part of a triple that sums to zero if and only if the value-(a[i]+ a[j])is in the array (but not a[i] or a[j] ).

-----------------

ThreeSum.java

import java.util.Arrays;

public class ThreeSum {
   public static int count(int[] a) {
      int n = a.length;
      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++;
            }
         }
      }
      return count;
   }

   public static void main(String[] args) {
      In in = new In("8Kints.txt");
      int[] a = in.readAllInts();

      System.out.println("The original array of ints: " + Arrays.toString(a));

      long startTime = System.currentTimeMillis();
      System.out.println("Count is: " + ThreeSum.count(a));
      long endTime = System.currentTimeMillis();
      long timeElapsed = endTime - startTime;
      System.out.println("Execution time in milliseconds  : " + timeElapsed);
   }
}

---------------

8ints.txt

8
-12
9
2
4
-9
-2
5

------------

Solutions

Expert Solution

Solution :

Simply sort the array.

Assign 'left' the leftmost index and 'right' the rightmost index and start iteration from the 0th index

At every index check for the condition of sum of the elements to be equal to 0, If the sum is 0,increment left and decrement right, else if sum is greater than 0, decrement right else increment index.

Repeat the above steps and update count.

Following is the Java code for same :

import java.util.*;

class ThreeSum {
  public static int count(int[] a) {
    int count=0;
    //sort the array
    Arrays.sort(a);
    for (int i = 0; i < a.length; i++) {
      int left = i + 1;
      int right = a.length - 1;
      while (left < right) {
        if (a[i] == -( a[left] + a[right])) {
          count++;
          left++;
          right--;
        } else if (a[i] + a[left] + a[right] < 0) {
          left++;
        } else {
          right--;
        }
      }
    }
    return count;
  }

   public static void main(String[] args) {
      
      In in = new In("8Kints.txt");
      int[] a = in.readAllInts();

      System.out.println("The original array of ints: " + Arrays.toString(a));

      long startTime = System.currentTimeMillis();
      System.out.println("Count is: " + Main.count(a));
      long endTime = System.currentTimeMillis();
      long timeElapsed = endTime - startTime;
      System.out.println("Execution time in milliseconds  : " + timeElapsed);
   }
}

Related Solutions

Problem 5: writing a faster implementation For this homework assignment, you will write a faster implementation...
Problem 5: writing a faster implementation For this homework assignment, you will write a faster implementation of do_insertions_simple (which we will call do_insertions_fast). We won't need anything extra (no special modules, no advanced algorithms, no Numpy) in order to obtain a considerable speedup. Let's think about what makes do_insertions_simple slow, and about how we can rewrite the whole thing in a faster way. The biggest problem with do_insertions_simple is that it calls insert once for every element of the insertions...
I NEED AN NLOGN OR LINEAR SOLUTION TO THIS PROBLEM! I NEED A FASTER SOLUTION THAN...
I NEED AN NLOGN OR LINEAR SOLUTION TO THIS PROBLEM! I NEED A FASTER SOLUTION THAN THE ONE GIVEN BELOW!! The solution below runs in quadratic time, I need one faster than this. I REPEAT I NEED A FASTER SOLUTION!! THE SOLUTION GIVEN BELOW IS TOO SLOW! Slow Solution: def predictAnswer(stockData, queries): stockData = [0] + stockData length = len(stockData) ans = [] for q in queries: l = q-1 r = q+1 flag = True while l > 0...
1. Find the big−O, big−Ω estimate for x7y3+x5y5+x3y7. [Hint: Big-O, big- Θ, and big-Omega notation can...
1. Find the big−O, big−Ω estimate for x7y3+x5y5+x3y7. [Hint: Big-O, big- Θ, and big-Omega notation can be extended to functions in more than one variable. For example, the statement f(x, y) is O(g(x, y)) means that there exist constants C, k1, and k2 such that|f(x, y)|≤C|g(x, y)|whenever x > k1 and y > k2] 2. Find a div b and a mod b when: (a) a = 30303, b = 333 (b) a = −765432, b = 3827 3. Convert...
How to determine whether the following statements about big-O notation are true or false? (a) Let...
How to determine whether the following statements about big-O notation are true or false? (a) Let f(n) = √ n log n − 4, then f(n) = O(n^ 2) (b) Let f(n) = 4 n + 2 log^ 2 (n), then f(n) = O(log^ 2 (n)) (c) Let f(n) = 5 √ n + 2, then f(n) = Ω(log^ 4 (n)) (d) Let f(n) = 5 n^ 2 + 5 n log n + 4, then f(n) = O(n^3 )...
Match the following functions to their respective big-O notation 1. 5 + 0.001n3 + 0.025n 2....
Match the following functions to their respective big-O notation 1. 5 + 0.001n3 + 0.025n 2. 100nlog n + n5 + 100n 3. n2log n + nlog n 4. 2n + n5 + 5n 5. 100n + 0.01n2 A. O(n3) B. O(5n) C. O(n2) D. O(n5) E. O(n2log n)
• Overview of Health Promotion Topic o Introduce cancer o Describe what cancer is o Explain...
• Overview of Health Promotion Topic o Introduce cancer o Describe what cancer is o Explain why it is a problem related to health and nursing o Provide references please, using APA format
5. What are the costs of “Big Cities”? What is the Urban Giantism Problem?
5. What are the costs of “Big Cities”? What is the Urban Giantism Problem?
(a) Explain the difference between big-O and big-theta, and give examples of each to show the...
(a) Explain the difference between big-O and big-theta, and give examples of each to show the difference. (b) How can we say that two functions have the same asymptotic complexity, using big-theta notation? (c) Rank the following functions in order of increasing complexity (rate of growth), and indicate which functions have the same asymptotic complexity. x2; x log(x); 2x; log(x) + 7; 92x2 + 57x + 3921; 4x; 27x2 + 8x3; 22x+5; log(x42); 3x + 12.
For the following LP problem, determine the optimal solution by the graphical solution method. Min Z=...
For the following LP problem, determine the optimal solution by the graphical solution method. Min Z= 3x1+2x2 Subject to 2x1+x2 >10                    -3x1+2x2 < 6                      X1+x2 > 6                      X1,x1 > 0 Graph and shade the feasible region
For the following linear programming problem, determine the optimal solution by the graphical solution method Max...
For the following linear programming problem, determine the optimal solution by the graphical solution method Max -x + 2y s.t. 6x - 2y <= 3 -2x + 3y <= 6     x +   y <= 3         x, y >= 0
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT