Mark As Completed Discussion

Good afternoon! Here's our prompt for today.

Given a linked list, can you write a method to get a random node within it? Let's assume you're given a random node generator. The linked list will have at least 2 nodes, and may look something like this:

1 -> 2 -> 3 -> 4

The odds of getting any number between 1 and 4 inclusive should be the exactly the same.

Description

You have access to this definition of a Linked List node:

JAVASCRIPT
1function Node(val) {
2  this.val = val;
3  this.next = null;
4}

Constraints

  • Length of the linked list <= 10000
  • The nodes will always contain integer values between -1000000000 and 1000000000
  • Expected time complexity : O(n)
  • Expected space complexity : O(n)

Try to solve this here or in Interactive Mode.

How do I practice this challenge?

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Tired of reading? Watch this video explanation!

To change the speed of the video or see it in full screen, click the icons to the right of the progress bar.

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.

Returning members can login to stop seeing this.