{ "data": { "question": { "questionId": "284", "questionFrontendId": "284", "boundTopicId": null, "title": "Peeking Iterator", "titleSlug": "peeking-iterator", "content": "
Design an iterator that supports the peek
operation on an existing iterator in addition to the hasNext
and the next
operations.
Implement the PeekingIterator
class:
PeekingIterator(Iterator<int> nums)
Initializes the object with the given integer iterator iterator
.int next()
Returns the next element in the array and moves the pointer to the next element.boolean hasNext()
Returns true
if there are still elements in the array.int peek()
Returns the next element in the array without moving the pointer.Note: Each language may have a different implementation of the constructor and Iterator
, but they all support the int next()
and boolean hasNext()
functions.
\n
Example 1:
\n\n\nInput\n["PeekingIterator", "next", "peek", "next", "next", "hasNext"]\n[[[1, 2, 3]], [], [], [], [], []]\nOutput\n[null, 1, 2, 2, 3, false]\n\nExplanation\nPeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3]\npeekingIterator.next(); // return 1, the pointer moves to the next element [1,2,3].\npeekingIterator.peek(); // return 2, the pointer does not move [1,2,3].\npeekingIterator.next(); // return 2, the pointer moves to the next element [1,2,3]\npeekingIterator.next(); // return 3, the pointer moves to the next element [1,2,3]\npeekingIterator.hasNext(); // return False\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= 1000
next
and peek
are valid.1000
calls will be made to next
, hasNext
, and peek
.\nFollow up: How would you extend your design to be generic and work with all types, not just integer?", "translatedTitle": null, "translatedContent": null, "isPaidOnly": false, "difficulty": "Medium", "likes": 988, "dislikes": 681, "isLiked": null, "similarQuestions": "[{\"title\": \"Binary Search Tree Iterator\", \"titleSlug\": \"binary-search-tree-iterator\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Flatten 2D Vector\", \"titleSlug\": \"flatten-2d-vector\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Zigzag Iterator\", \"titleSlug\": \"zigzag-iterator\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "exampleTestcases": "[\"PeekingIterator\",\"next\",\"peek\",\"next\",\"next\",\"hasNext\"]\n[[[1,2,3]],[],[],[],[],[]]", "categoryTitle": "Algorithms", "contributors": [], "topicTags": [ { "name": "Array", "slug": "array", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Design", "slug": "design", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Iterator", "slug": "iterator", "translatedName": null, "__typename": "TopicTagNode" } ], "companyTagStats": null, "codeSnippets": [ { "lang": "C++", "langSlug": "cpp", "code": "/*\n * Below is the interface for Iterator, which is already defined for you.\n * **DO NOT** modify the interface for Iterator.\n *\n * class Iterator {\n *\t\tstruct Data;\n * \t\tData* data;\n * public:\n *\t\tIterator(const vector
peek()
before next()
vs next()
before peek()
.",
"For a clean implementation, check out Google's guava library source code."
],
"solution": {
"id": "879",
"canSeeDetail": false,
"paidOnly": true,
"hasVideoSolution": false,
"paidOnlyVideo": true,
"__typename": "ArticleNode"
},
"status": null,
"sampleTestCase": "[\"PeekingIterator\",\"next\",\"peek\",\"next\",\"next\",\"hasNext\"]\n[[[1,2,3]],[],[],[],[],[]]",
"metaData": "{\n \"name\": \"PeekingIterator\",\n \"params\": [\n {\n \"name\": \"nums\",\n \"type\": \"listCompiled with clang 11
using the latest C++ 17 standard.
Your code is compiled with level two optimization (-O2
). AddressSanitizer is also enabled to help detect out-of-bounds and use-after-free bugs.
Most standard library headers are already included automatically for your convenience.
\"], \"java\": [\"Java\", \" OpenJDK 17
. Java 8 features such as lambda expressions and stream API can be used.
Most standard library headers are already included automatically for your convenience.
\\r\\nIncludes Pair
class from https://docs.oracle.com/javase/8/javafx/api/javafx/util/Pair.html.
Python 2.7.12
.
Most libraries are already imported automatically for your convenience, such as array, bisect, collections. If you need more libraries, you can import it yourself.
\\r\\n\\r\\nFor Map/TreeMap data structure, you may use sortedcontainers library.
\\r\\n\\r\\nNote that Python 2.7 will not be maintained past 2020. For the latest Python, please choose Python3 instead.
\"], \"c\": [\"C\", \"Compiled with gcc 8.2
using the gnu99 standard.
Your code is compiled with level one optimization (-O1
). AddressSanitizer is also enabled to help detect out-of-bounds and use-after-free bugs.
Most standard library headers are already included automatically for your convenience.
\\r\\n\\r\\nFor hash table operations, you may use uthash. \\\"uthash.h\\\" is included by default. Below are some examples:
\\r\\n\\r\\n1. Adding an item to a hash.\\r\\n
\\r\\nstruct hash_entry {\\r\\n int id; /* we'll use this field as the key */\\r\\n char name[10];\\r\\n UT_hash_handle hh; /* makes this structure hashable */\\r\\n};\\r\\n\\r\\nstruct hash_entry *users = NULL;\\r\\n\\r\\nvoid add_user(struct hash_entry *s) {\\r\\n HASH_ADD_INT(users, id, s);\\r\\n}\\r\\n\\r\\n\\r\\n\\r\\n
2. Looking up an item in a hash:\\r\\n
\\r\\nstruct hash_entry *find_user(int user_id) {\\r\\n struct hash_entry *s;\\r\\n HASH_FIND_INT(users, &user_id, s);\\r\\n return s;\\r\\n}\\r\\n\\r\\n\\r\\n\\r\\n
3. Deleting an item in a hash:\\r\\n
\\r\\nvoid delete_user(struct hash_entry *user) {\\r\\n HASH_DEL(users, user); \\r\\n}\\r\\n\\r\\n\"], \"csharp\": [\"C#\", \"\\r\\n\\r\\n
Your code is compiled with debug flag enabled (/debug
).
Node.js 16.13.2
.
Your code is run with --harmony
flag, enabling new ES6 features.
lodash.js library is included by default.
\\r\\n\\r\\nFor Priority Queue / Queue data structures, you may use datastructures-js/priority-queue and datastructures-js/queue.
\"], \"ruby\": [\"Ruby\", \"Ruby 3.1
Some common data structure implementations are provided in the Algorithms module: https://www.rubydoc.info/github/kanwei/algorithms/Algorithms
\"], \"swift\": [\"Swift\", \"Swift 5.5.2
.
Go 1.17.6
.
Support https://godoc.org/github.com/emirpasic/gods library.
\"], \"python3\": [\"Python3\", \"Python 3.10
.
Most libraries are already imported automatically for your convenience, such as array, bisect, collections. If you need more libraries, you can import it yourself.
\\r\\n\\r\\nFor Map/TreeMap data structure, you may use sortedcontainers library.
\"], \"scala\": [\"Scala\", \"Scala 2.13.7
.
Kotlin 1.3.10
.
PHP 8.1
.
With bcmath module
\"], \"typescript\": [\"Typescript\", \"TypeScript 4.5.4, Node.js 16.13.2
.
Your code is run with --harmony
flag, enabling new ES2020 features.
lodash.js library is included by default.
\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": null, "__typename": "QuestionNode" } } }