LeetCode: Flatten Nested List Iterator Solution
1/**2 * // This is the interface that allows for creating nested lists.3 * // You should not implement it, or speculate about its implementation4 * function NestedInteger() {5 *6 * Return true if this NestedInteger holds a single integer, rather than a nested list.7 * @return {boolean}8 * this.isInteger = function() {9 * ...10 * };11 *12 * Return the single integer that this NestedInteger holds, if it holds a single integer13 * Return null if this NestedInteger holds a nested list14 * @return {integer}15 * this.getInteger = function() {16 * ...17 * };18 *19 * Return the nested list that this NestedInteger holds, if it holds a nested list20 * Return null if this NestedInteger holds a single integer21 * @return {NestedInteger[]}22 * this.getList = function() {23 * ...24 * };25 * };26 */27/**28 * @constructor29 * @param {NestedInteger[]} nestedList30 */3132const flatten = nestedList => {33 return nestedList.flatMap(nestedInteger =>34 nestedInteger.isInteger()35 ? nestedInteger.getInteger()36 : flatten(nestedInteger.getList())37 )38}3940var NestedIterator = function (nestedList) {41 this.array = flatten(nestedList)42}4344/**45 * @this NestedIterator46 * @returns {boolean}47 */48NestedIterator.prototype.hasNext = function () {49 return this.array.length50}5152/**53 * @this NestedIterator54 * @returns {integer}55 */56NestedIterator.prototype.next = function () {57 return this.array.shift()58}5960/**61 * Your NestedIterator will be called like this:62 * var i = new NestedIterator(nestedList), a = [];63 * while (i.hasNext()) a.push(i.next());64 */
Comments
Loading comments...
Tags
leetcode
stack
recursion
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.