{ "data": { "question": { "questionId": "766", "questionFrontendId": "430", "boundTopicId": null, "title": "Flatten a Multilevel Doubly Linked List", "titleSlug": "flatten-a-multilevel-doubly-linked-list", "content": "

You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below.

\n\n

Given the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list.

\n\n

Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null.

\n\n

 

\n

Example 1:

\n\"\"\n
\nInput: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]\nOutput: [1,2,3,7,8,11,12,9,10,4,5,6]\nExplanation: The multilevel linked list in the input is shown.\nAfter flattening the multilevel linked list it becomes:\n\n
\n\n

Example 2:

\n\"\"\n
\nInput: head = [1,2,null,3]\nOutput: [1,3,2]\nExplanation: The multilevel linked list in the input is shown.\nAfter flattening the multilevel linked list it becomes:\n\n
\n\n

Example 3:

\n\n
\nInput: head = []\nOutput: []\nExplanation: There could be empty list in the input.\n
\n\n

 

\n

Constraints:

\n\n\n\n

 

\n

How the multilevel linked list is represented in test cases:

\n\n

We use the multilevel linked list from Example 1 above:

\n\n
\n 1---2---3---4---5---6--NULL\n         |\n         7---8---9---10--NULL\n             |\n             11--12--NULL
\n\n

The serialization of each level is as follows:

\n\n
\n[1,2,3,4,5,6,null]\n[7,8,9,10,null]\n[11,12,null]\n
\n\n

To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:

\n\n
\n[1,    2,    3, 4, 5, 6, null]\n             |\n[null, null, 7,    8, 9, 10, null]\n                   |\n[            null, 11, 12, null]\n
\n\n

Merging the serialization of each level and removing trailing nulls we obtain:

\n\n
\n[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]\n
\n", "translatedTitle": null, "translatedContent": null, "isPaidOnly": false, "difficulty": "Medium", "likes": 3596, "dislikes": 251, "isLiked": null, "similarQuestions": "[{\"title\": \"Flatten Binary Tree to Linked List\", \"titleSlug\": \"flatten-binary-tree-to-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Correct a Binary Tree\", \"titleSlug\": \"correct-a-binary-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "exampleTestcases": "[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]\n[1,2,null,3]\n[]", "categoryTitle": "Algorithms", "contributors": [], "topicTags": [ { "name": "Linked List", "slug": "linked-list", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Depth-First Search", "slug": "depth-first-search", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Doubly-Linked List", "slug": "doubly-linked-list", "translatedName": null, "__typename": "TopicTagNode" } ], "companyTagStats": null, "codeSnippets": [ { "lang": "C++", "langSlug": "cpp", "code": "/*\n// Definition for a Node.\nclass Node {\npublic:\n int val;\n Node* prev;\n Node* next;\n Node* child;\n};\n*/\n\nclass Solution {\npublic:\n Node* flatten(Node* head) {\n \n }\n};", "__typename": "CodeSnippetNode" }, { "lang": "Java", "langSlug": "java", "code": "/*\n// Definition for a Node.\nclass Node {\n public int val;\n public Node prev;\n public Node next;\n public Node child;\n};\n*/\n\nclass Solution {\n public Node flatten(Node head) {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Python", "langSlug": "python", "code": "\"\"\"\n# Definition for a Node.\nclass Node(object):\n def __init__(self, val, prev, next, child):\n self.val = val\n self.prev = prev\n self.next = next\n self.child = child\n\"\"\"\n\nclass Solution(object):\n def flatten(self, head):\n \"\"\"\n :type head: Node\n :rtype: Node\n \"\"\"\n ", "__typename": "CodeSnippetNode" }, { "lang": "Python3", "langSlug": "python3", "code": "\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val, prev, next, child):\n self.val = val\n self.prev = prev\n self.next = next\n self.child = child\n\"\"\"\n\nclass Solution:\n def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]':\n ", "__typename": "CodeSnippetNode" }, { "lang": "C#", "langSlug": "csharp", "code": "/*\n// Definition for a Node.\npublic class Node {\n public int val;\n public Node prev;\n public Node next;\n public Node child;\n}\n*/\n\npublic class Solution {\n public Node Flatten(Node head) {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "JavaScript", "langSlug": "javascript", "code": "/**\n * // Definition for a Node.\n * function Node(val,prev,next,child) {\n * this.val = val;\n * this.prev = prev;\n * this.next = next;\n * this.child = child;\n * };\n */\n\n/**\n * @param {Node} head\n * @return {Node}\n */\nvar flatten = function(head) {\n \n};", "__typename": "CodeSnippetNode" }, { "lang": "Ruby", "langSlug": "ruby", "code": "# Definition for a Node.\n# class Node\n# attr_accessor :val, :prev, :next, :child\n# def initialize(val=nil, prev=nil, next_=nil, child=nil)\n# @val = val\n# @prev = prev\n# @next = next_\n# @child = child\n# end\n# end\n\n# @param {Node} root\n# @return {Node}\ndef flatten(root)\n \nend", "__typename": "CodeSnippetNode" }, { "lang": "Swift", "langSlug": "swift", "code": "/**\n * Definition for a Node.\n * public class Node {\n * public var val: Int\n * public var prev: Node?\n * public var next: Node?\n * public var child: Node?\n * public init(_ val: Int) {\n * self.val = val\n * self.prev = nil\n * self.next = nil\n * self.child = nil\n * }\n * }\n */\n\nclass Solution {\n func flatten(_ head: Node?) -> Node? {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Go", "langSlug": "golang", "code": "/**\n * Definition for a Node.\n * type Node struct {\n * Val int\n * Prev *Node\n * Next *Node\n * Child *Node\n * }\n */\n\nfunc flatten(root *Node) *Node {\n \n}", "__typename": "CodeSnippetNode" }, { "lang": "Scala", "langSlug": "scala", "code": "/**\n * Definition for a Node.\n * class Node(var _value: Int) {\n * var value: Int = _value\n * var prev: Node = null\n * var next: Node = null\n * var child: Node = null\n * }\n */\n\nobject Solution {\n def flatten(head: Node): Node = {\n \t\n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Kotlin", "langSlug": "kotlin", "code": "/**\n * Definition for a Node.\n * class Node(var `val`: Int) {\n * var prev: Node? = null\n * var next: Node? = null\n * var child: Node? = null\n * }\n */\n\nclass Solution {\n fun flatten(root: Node?): Node? {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "PHP", "langSlug": "php", "code": "/**\n * Definition for a Node.\n * class Node {\n * public $val = null;\n * public $prev = null;\n * public $next = null;\n * public $child = null;\n * function __construct($val = 0) {\n * $this->val = $val;\n * $this->prev = null;\n * $this->next = null;\n * $this->child = null;\n * }\n * }\n */\n\nclass Solution {\n /**\n * @param Node $head\n * @return Node\n */\n function flatten($head) {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "TypeScript", "langSlug": "typescript", "code": "/**\n * Definition for node.\n * class Node {\n * val: number\n * prev: Node | null\n * next: Node | null\n * child: Node | null\n * constructor(val?: number, prev? : Node, next? : Node, child? : Node) {\n * this.val = (val===undefined ? 0 : val);\n * this.prev = (prev===undefined ? null : prev);\n * this.next = (next===undefined ? null : next);\n * this.child = (child===undefined ? null : child);\n * }\n * }\n */\n\nfunction flatten(head: Node | null): Node | null {\n\n};", "__typename": "CodeSnippetNode" } ], "stats": "{\"totalAccepted\": \"230.3K\", \"totalSubmission\": \"391K\", \"totalAcceptedRaw\": 230315, \"totalSubmissionRaw\": 390988, \"acRate\": \"58.9%\"}", "hints": [], "solution": { "id": "827", "canSeeDetail": false, "paidOnly": true, "hasVideoSolution": false, "paidOnlyVideo": true, "__typename": "ArticleNode" }, "status": null, "sampleTestCase": "[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]", "metaData": "{\n \"name\": \"flatten\",\n \"params\": [\n {\n \"name\": \"head\",\n \"type\": \"ListNode\"\n }\n ],\n \"return\": {\n \"type\": \"ListNode\"\n },\n \"languages\": [\n \"cpp\",\n \"java\",\n \"python\",\n \"csharp\",\n \"javascript\",\n \"python3\",\n \"kotlin\",\n \"ruby\",\n \"scala\",\n \"golang\",\n \"swift\",\n \"php\",\n \"typescript\"\n ],\n \"manual\": true\n}", "judgerAvailable": true, "judgeType": "large", "mysqlSchemas": [], "enableRunCode": true, "enableTestMode": false, "enableDebugger": true, "envInfo": "{\"cpp\": [\"C++\", \"

Compiled with clang 11 using the latest C++ 17 standard.

\\r\\n\\r\\n

Your code is compiled with level two optimization (-O2). AddressSanitizer is also enabled to help detect out-of-bounds and use-after-free bugs.

\\r\\n\\r\\n

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.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\\r\\n

Includes Pair class from https://docs.oracle.com/javase/8/javafx/api/javafx/util/Pair.html.

\"], \"python\": [\"Python\", \"

Python 2.7.12.

\\r\\n\\r\\n

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\\n

For Map/TreeMap data structure, you may use sortedcontainers library.

\\r\\n\\r\\n

Note that Python 2.7 will not be maintained past 2020. For the latest Python, please choose Python3 instead.

\"], \"csharp\": [\"C#\", \"

C# 10 with .NET 6 runtime

\\r\\n\\r\\n

Your code is compiled with debug flag enabled (/debug).

\"], \"javascript\": [\"JavaScript\", \"

Node.js 16.13.2.

\\r\\n\\r\\n

Your code is run with --harmony flag, enabling new ES6 features.

\\r\\n\\r\\n

lodash.js library is included by default.

\\r\\n\\r\\n

For Priority Queue / Queue data structures, you may use datastructures-js/priority-queue and datastructures-js/queue.

\"], \"ruby\": [\"Ruby\", \"

Ruby 3.1

\\r\\n\\r\\n

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.

\"], \"golang\": [\"Go\", \"

Go 1.17.6.

\\r\\n\\r\\n

Support https://godoc.org/github.com/emirpasic/gods library.

\"], \"python3\": [\"Python3\", \"

Python 3.10.

\\r\\n\\r\\n

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\\n

For Map/TreeMap data structure, you may use sortedcontainers library.

\"], \"scala\": [\"Scala\", \"

Scala 2.13.7.

\"], \"kotlin\": [\"Kotlin\", \"

Kotlin 1.3.10.

\"], \"php\": [\"PHP\", \"

PHP 8.1.

\\r\\n

With bcmath module

\"], \"typescript\": [\"Typescript\", \"

TypeScript 4.5.4, Node.js 16.13.2.

\\r\\n\\r\\n

Your code is run with --harmony flag, enabling new ES2020 features.

\\r\\n\\r\\n

lodash.js library is included by default.

\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": null, "__typename": "QuestionNode" } } }