Good morning! Here's our prompt for today.
Now that we've implemented a Linked List, let's start operating on it! Assume you have a Linked List implementation with this definition:
JAVASCRIPT
1class LinkedList {
2 constructor() {
3 this.head = null;
4 this.tail = null;
5 }
6
7 prepend(newVal) {
8 const currentHead = this.head;
9 const newNode = new Node(newVal);
10 newNode.next = currentHead;
11 this.head = newNode;
12
13 if (!this.tail) {
14 this.tail = newNode;
15 }
16 }
17
18 append(newVal) {
19 const newNode = new Node(newVal);
20 if (!this.head) {
21 this.head = newNode;
22 this.tail = newNode;
23 } else {
24 this.tail.next = newNode;
25 this.tail = newNode;
26 }
27 }
28}
Can you write a method getUnion
to find the union of two linked lists? A union of two sets includes everything in both sets.

So given 1 -> 2 -> 3
and 3 -> 4 -> 5
, we'd get 1 -> 2 -> 3 -> 4 -> 5
.
Constraints
- Length of both the linkedlist <=
1000
- The nodes will always contain integer values between
-1000000000
and1000000000
- Let
m, n
be the lengths of the two lists - Expected time complexity :
O(n*m)
- Expected space complexity :
O(n+m)
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
98
'PASSED: Expected the following: `let list1 = new LinkedList; list1.prepend(25); list1.prepend(15); list1.prepend(5); list1.prepend(9); let list2 = new LinkedList; list2.prepend(14); list2.prepend(15); list2.prepend(7); list2.prepend(13); getUnion(list1, list2).toArray();`to have members `[13, 7, 14, 25, 15, 5, 9]`'
function getUnion(list1, list2) {
// implement a method to get the union
}
​
function Node(val) {
this.val = val;
this.next = null;
}
​
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
​
prepend(newVal) {
const currentHead = this.head;
const newNode = new Node(newVal);
newNode.next = currentHead;
this.head = newNode;
​
if (!this.tail) {
this.tail = newNode;
}
}
​
append(newVal) {
const newNode = new Node(newVal);
if (!this.head) {
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Here's how we would solve this problem...
How do I use this guide?
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.