Skip to content

Commit aa7d383

Browse files
committed
Create 284-peeking_iterator.py
1 parent 3eb5775 commit aa7d383

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

284-peeking_iterator.py

+87
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
"""
2+
https://leetcode.com/problems/peeking-iterator/
3+
4+
Strat:
5+
Store (cache) the next element we should return, along with if
6+
we have an additional element to return. Have to ensure we turn
7+
our iterator into
8+
9+
Stats: O(n) / linear time, O(n) / linear space
10+
Runtime: 16 ms, faster than 94.98% of Python online submissions for Peeking Iterator.
11+
Memory Usage: 12.7 MB, less than 93.31% of Python online submissions for Peeking Iterator.
12+
13+
Clean solution by Stefan: https://leetcode.com/problems/peeking-iterator/discuss/72557/NexthasNext-use-peek
14+
"""
15+
class PeekingIterator(object):
16+
def __init__(self, iterator):
17+
"""
18+
Initialize your data structure here.
19+
:type iterator: Iterator
20+
"""
21+
#make our vars accessible within whole class by using self
22+
self.iterator = iterator
23+
24+
#try to init our vars used for caching
25+
if self.iterator.hasNext():
26+
self.cached_has_next = True
27+
self.cached_next = iterator.next()
28+
else:
29+
self.cached_has_next = False
30+
31+
32+
def peek(self):
33+
"""
34+
Returns the next element in the iteration without advancing the iterator.
35+
:rtype: int
36+
"""
37+
return self.cached_next
38+
39+
40+
def next(self):
41+
"""
42+
:rtype: int
43+
"""
44+
tmp = self.cached_next
45+
46+
#see if we can call next() again
47+
if self.iterator.hasNext():
48+
#update cached_next with new element
49+
self.cached_next = self.iterator.next()
50+
else:
51+
self.cached_has_next = False
52+
53+
#return the prev elem which was stored in tmp
54+
return tmp
55+
56+
57+
def hasNext(self):
58+
"""
59+
:rtype: bool
60+
"""
61+
return self.cached_has_next
62+
63+
64+
# class Iterator(object):
65+
# def __init__(self, nums):
66+
# """
67+
# Initializes an iterator object to the beginning of a list.
68+
# :type nums: List[int]
69+
# """
70+
#
71+
# def hasNext(self):
72+
# """
73+
# Returns true if the iteration has more elements.
74+
# :rtype: bool
75+
# """
76+
#
77+
# def next(self):
78+
# """
79+
# Returns the next element in the iteration.
80+
# :rtype: int
81+
# """
82+
83+
# Your PeekingIterator object will be instantiated and called as such:
84+
# iter = PeekingIterator(Iterator(nums))
85+
# while iter.hasNext():
86+
# val = iter.peek() # Get the next element but not advance the iterator.
87+
# iter.next() # Should return the same value as [val].

0 commit comments

Comments
 (0)