|
| 1 | +<p>Design an algorithm that accepts a stream of integers and retrieves the product of the last <code>k</code> integers of the stream.</p> |
| 2 | + |
| 3 | +<p>Implement the <code>ProductOfNumbers</code> class:</p> |
| 4 | + |
| 5 | +<ul> |
| 6 | + <li><code>ProductOfNumbers()</code> Initializes the object with an empty stream.</li> |
| 7 | + <li><code>void add(int num)</code> Appends the integer <code>num</code> to the stream.</li> |
| 8 | + <li><code>int getProduct(int k)</code> Returns the product of the last <code>k</code> numbers in the current list. You can assume that always the current list has at least <code>k</code> numbers.</li> |
| 9 | +</ul> |
| 10 | + |
| 11 | +<p>The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing.</p> |
| 12 | + |
| 13 | +<p> </p> |
| 14 | +<p><strong class="example">Example:</strong></p> |
| 15 | + |
| 16 | +<pre> |
| 17 | +<strong>Input</strong> |
| 18 | +["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"] |
| 19 | +[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]] |
| 20 | + |
| 21 | +<strong>Output</strong> |
| 22 | +[null,null,null,null,null,null,20,40,0,null,32] |
| 23 | + |
| 24 | +<strong>Explanation</strong> |
| 25 | +ProductOfNumbers productOfNumbers = new ProductOfNumbers(); |
| 26 | +productOfNumbers.add(3); // [3] |
| 27 | +productOfNumbers.add(0); // [3,0] |
| 28 | +productOfNumbers.add(2); // [3,0,2] |
| 29 | +productOfNumbers.add(5); // [3,0,2,5] |
| 30 | +productOfNumbers.add(4); // [3,0,2,5,4] |
| 31 | +productOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 * 4 = 20 |
| 32 | +productOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 * 5 * 4 = 40 |
| 33 | +productOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 * 2 * 5 * 4 = 0 |
| 34 | +productOfNumbers.add(8); // [3,0,2,5,4,8] |
| 35 | +productOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 * 8 = 32 |
| 36 | +</pre> |
| 37 | + |
| 38 | +<p> </p> |
| 39 | +<p><strong>Constraints:</strong></p> |
| 40 | + |
| 41 | +<ul> |
| 42 | + <li><code>0 <= num <= 100</code></li> |
| 43 | + <li><code>1 <= k <= 4 * 10<sup>4</sup></code></li> |
| 44 | + <li>At most <code>4 * 10<sup>4</sup></code> calls will be made to <code>add</code> and <code>getProduct</code>.</li> |
| 45 | + <li>The product of the stream at any point in time will fit in a <strong>32-bit</strong> integer.</li> |
| 46 | +</ul> |
| 47 | + |
| 48 | +<p> </p> |
| 49 | +<strong>Follow-up: </strong>Can you implement <strong>both</strong> <code>GetProduct</code> and <code>Add</code> to work in <code>O(1)</code> time complexity instead of <code>O(k)</code> time complexity? |
0 commit comments