Note that there are some explanatory texts on larger screens.

plurals
  1. POgiven a set of n integers, return all subsets of k elements that sum to 0
    primarykey
    data
    text
    <p>given a unsorted set of <code>n</code> integers, return all subsets of size k (i.e. each set has k unique elements) that sum to 0.</p> <p>So I gave the interviewer the following solution ( which I studied on <a href="http://geekviewpoint.com/Numbers_functions_in_java/" rel="noreferrer">GeekViewpoint</a>). No extra space used, everything is done in place, etc. But of course the cost is a high time complexity of O(n^k) where <code>k=tuple</code> in the solution.</p> <pre><code>public void zeroSumTripplets(int[] A, int tuple, int sum) { int[] index = new int[tuple]; for (int i = 0; i &lt; tuple; i++) index[i] = i; int total = combinationSize(A.length, tuple); for (int i = 0; i &lt; total; i++) { if (0 != i) nextCombination(index, A.length, tuple); printMatch(A, Arrays.copyOf(index, tuple), sum); }// for }// zeroSumTripplets(int[], int, int) private void printMatch(int[] A, int[] ndx, int sum) { int calc = 0; for (int i = 0; i &lt; ndx.length; i++) calc += A[ndx[i]]; if (calc == sum) { Integer[] t = new Integer[ndx.length]; for (int i = 0; i &lt; ndx.length; i++) t[i] = A[ndx[i]]; System.out.println(Arrays.toString(t)); }// if }// printMatch(int[], int[], int) </code></pre> <p>But then she imposed the following requirements: </p> <ul> <li>must use hashmap in answer so to reduce time complexity</li> <li>Must absolutely -- ABSOLUTELY -- provide time complexity for general case</li> <li>hint when k=6, O(n^3)</li> </ul> <p>She was more interested in time-complexity more than anything else.</p> <p>Does anyone know a solution that would satisfy the new constraints?</p> <hr> <p>EDIT:</p> <p>Supposedly, in the correct solution, the map is to store the elements of the input and the map is then to be used as a look up table just as in the case for <code>k=2</code>. </p> <p>When the size of the subset is 2 (i.e. <code>k=2</code>), the answer is trivial: loop through and load all the elements into a map. Then loop through the inputs again this time searching the map for <code>sum - input[i] where i is the index from 0 to n-1</code>, which would then be the answers. Supposedly this trivial case can be extended to where <code>k</code> is anything.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload