27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Solutions</strong> to Chapter 8 | Recursion<br />

8.3 Write a method that returns all subsets of a set.<br />

pg 64<br />

SOLUTION<br />

We should first have some reasonable expectations of our time <strong>and</strong> space complexity. How<br />

many subsets of a set are <strong>the</strong>re? We can compute this by realizing that when we generate a<br />

subset, each element has <strong>the</strong> “choice” of ei<strong>the</strong>r being in <strong>the</strong>re or not. That is, for <strong>the</strong> first element,<br />

<strong>the</strong>re are 2 choices. For <strong>the</strong> second, <strong>the</strong>re are two, etc. So, doing 2 * 2 * ... * 2 n times<br />

gives us 2^n subsets. We will not be able to do better than this in time or space complexity.<br />

Approach #1: Recursion<br />

This is a great problem to implement with recursion since we can build all subsets of a set using<br />

all subsets of a smaller set. Specifically, given a set S, we can do <strong>the</strong> following recursively:<br />

»»<br />

Let first = S[0]. Let smallerSet = S[1, ..., n].<br />

»»<br />

Compute all subsets of smallerSet <strong>and</strong> put <strong>the</strong>m in allsubsets.<br />

»»<br />

For each subset in allsubsets, clone it <strong>and</strong> add first to <strong>the</strong> subset.<br />

The following code implements this algorithm:<br />

1 ArrayList getSubsets(ArrayList set,<br />

2 int index) {<br />

3 ArrayList allsubsets;<br />

4 if (set.size() == index) {<br />

5 allsubsets = new ArrayList();<br />

6 allsubsets.add(new ArrayList()); // Empty set<br />

7 } else {<br />

8 allsubsets = getSubsets(set, index + 1);<br />

9 int item = set.get(index);<br />

10 ArrayList moresubsets =<br />

11 new ArrayList();<br />

12 for (ArrayList subset : allsubsets) {<br />

13 ArrayList newsubset = new ArrayList();<br />

14 newsubset.addAll(subset); //<br />

15 newsubset.add(item);<br />

16 moresubsets.add(newsubset);<br />

17 }<br />

18 allsubsets.addAll(moresubsets);<br />

19 }<br />

20 return allsubsets;<br />

21 }<br />

Approach #2: Combinatorics<br />

»»<br />

When we’re generating a set, we have two choices for each element: (1) <strong>the</strong> element is<br />

1 7 1<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Concepts <strong>and</strong> Algorithms

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!