# Problem:

Given a singly linked list, return a random node’s value from the linked list. Each node must have the same probability of being chosen.

What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?

Example:

# Solution:

C++

Time Complexity: O(n)

Space Complexity: O(1)

Problem:

Remove all elements from a linked list of integers that have value val.

Example
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5

Idea:

Solution:

Time complexity: O(n)

Space complexity: O(1)

C++

Problem:

Given a singly linked list, determine if it is a palindrome.

Could you do it in O(n) time and O(1) space?

Idea:

1. use fast / slow pointers to find the middle node and see whether the list has odd/even number of elements.
2. Reverse the right half the list, and compare with the left half

E.g.
1->2->3->4->3->2->1->null
fast = null
slow = 4
slow->next = 3
reverse(slow->next)
null<-3<-2<-1 compare with 1->2->3->…

Solution: 1

Time complexity: O(n)

Space complexity: O(1)

C++

Problem:

Solution 1:

Tracking prev / curr / next node

Time complexity: O(n)

Space complexity: O(1)

C++

Java

Python 3

Problem:

Given a (singly) linked list with head node root, write a function to split the linked list into k consecutive linked list “parts”.

The length of each part should be as equal as possible: no two parts should have a size differing by more than 1. This may lead to some parts being null.

The parts should be in order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal parts occurring later.

Return a List of ListNode’s representing the linked list parts that are formed.

Examples 1->2->3->4, k = 5 // 5 equal parts [ [1], [2], [3], [4], null ]

Example 1:

Example 2:

Note:

• The length of root will be in the range [0, 1000].
• Each value of a node in the input will be an integer in the range [0, 999].
• k will be an integer in the range [1, 50].

Idea:
List + Simulation
Solution:
C++

Java

Python

Mission News Theme by Compete Themes.