Adding all the solutions - #465
Conversation
|
Great job on both solutions! For the stock problem, your solution is optimal with O(n) time and O(1) space. The approach of summing all positive consecutive differences is perfect for this problem and is a common efficient solution. The code is clean and easy to understand. For the Peeking Iterator, your implementation is correct and efficient. You correctly store the next element to allow peeking without advancing. The code is well-organized and follows good object-oriented practices. One minor note for the Peeking Iterator: in the next() method, you should handle the case when there is no next element. Currently, if nextEl is null (meaning no more elements), calling next() would return null, which might be acceptable if the iterator only contains non-null integers, but the problem states that the iterator has integers. However, the Java Iterator contract for next() requires throwing a NoSuchElementException if there are no more elements. Your code does not throw an exception when nextEl is null and next() is called. You should adjust it to throw an exception in that case. For example: @Override
public Integer next() {
if (nextEl == null) {
throw new NoSuchElementException();
}
Integer result = nextEl;
nextEl = iter.hasNext() ? iter.next() : null;
return result;
}But since the problem says "hasNext() and next() should behave the same as in the Iterator interface", you should ensure next() throws when there are no more elements. Currently, your code returns null instead of throwing, which might not be correct. Please fix this. Other than that, both solutions are excellent. Keep up the good work! |
No description provided.