1579. Parity Split Chains

Easy1.5 points estimatedLinked List

A warehouse stores item codes in a singly linked list and wants to sort them onto two shelves, one for odd codes and one for even codes. Given head, return an array of exactly two lists: the first holds every node whose value is odd and the second holds every node whose value is even. A value is odd when its absolute value is odd, so -3 is odd and -4 is even, and 0 is even. Inside each list the nodes keep their original relative order. Reuse the existing nodes by relinking them, make sure each result list ends with a null next pointer, and use null for a part that has no nodes. Values lie between -10^9 and 10^9 and the list has 0 to 1000 nodes. Aim for O(n) time and O(1) extra space.

Example 1

Input:
head = [1,2,3,4,5]
Output:
[[1,3,5],[2,4]]
Explanation:

Odd values 1,3,5 go first and even values 2,4 second.

Example 2

Input:
head = [2,4,6]
Output:
[[],[2,4,6]]
Explanation:

No odd values, so the first list is null.

Example 3

Input:
head = [-3,-4,0,7]
Output:
[[-3,7],[-4,0]]
Explanation:

-3 and 7 are odd; -4 and 0 are even.

Constraints

0 ≤ length ≤ 1000

-109 ≤ val ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…