easy +8 pts

Difference of Consecutive Elements

Compute the differences between adjacent elements in a list.

Write a function `consecutive_differences(nums)` that takes a list of integers `nums` and returns a new list where each element at index `i` is the difference between the element at index `i+1` and the element at index `i` in the original list. The returned list will have length `len(nums) - 1`. For example, given `[5, 2, 8, 1]`, the result should be `[2-5, 8-2, 1-8] = [-3, 6, -7]`. If the input list has fewer than two elements, return an empty list.

Constraints

Input list length will be between 0 and 10^5. Each element is an integer (may be negative or large). Your solution should have O(n) time and O(1) extra space (not counting the output).

Example

>>> consecutive_differences([5, 2, 8, 1])
[-3, 6, -7]
>>> consecutive_differences([10, 20, 30])
[10, 10]
>>> consecutive_differences([7])
[]
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Think about how to relate each output element to a pair of neighboring input elements.
You can use a for loop with an index or zip the list with itself shifted by one.
If the length is less than 2, return an empty list directly.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.