1594. Chain Long Division

Medium3.5 points estimatedLinked ListMaths

A meter stores a large reading as a singly linked list of decimal digits, most significant digit first, and the clerk must split it evenly among d teams, where d is a single digit from 1 to 9. Write chainDivide(head, d), which performs long division from left to right, carrying the remainder from digit to digit, and returns the integer quotient as a new linked list of digits without leading zeros. If the quotient is 0, return a single node holding 0. The first digit of the input is non-zero unless the list has only one node. The list has 1 to 1000 nodes. Aim for O(n) time and O(1) extra space besides the answer.

Example 1

Input:
head = [1,2,3], d = 2
Output:
[6,1]
Explanation:

123 / 2 = 61.

Example 2

Input:
head = [7], d = 3
Output:
[2]
Explanation:

7 / 3 = 2 with remainder 1.

Example 3

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

1000 / 4 = 250.

Constraints

1 ≤ length ≤ 1000

0 ≤ val ≤ 9; the first digit is non-zero unless length = 1

1 ≤ d ≤ 9

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…