Magnitude order: Total receipt
Stuck or curious how this works? Visualize Sorting ↗
Inputs
readings is a list of integers (numbers with no decimal part). It may be empty, and numbers may repeat unless task 1 says otherwise.
Your tasks
- Create a list
byDistance. Sortreadingsby distance from 0, from nearest to farthest. This distance is called absolute value: both -4 and 4 have distance 4. When two numbers have the same distance, put the smaller number first. Keep all repeated numbers. For [3, -2, 2, -3],byDistanceis [-2, 2, -3, 3]. - Add up every number in
byDistance. Store the sum intotal. - Complete
magnitudeOrderTotalReceiptso it returnstotal. Return it, do not print it.
Example
If readings is [6, 6, 7, -7, 10], then byDistance is [6, 6, -7, 7, 10] and magnitudeOrderTotalReceipt returns 22.
Rules
- If
byDistanceis empty,totalis 0.
Test data
TEST DATA 1: readings is [-5, 4, 0, 4, 6].
TEST DATA 2: readings is [-5, 8, 8, 8].
Examples
Input: readings = [-5,4,0,4,6] Output: 9
byDistance is [0, 4, 4, -5, 6]. Add its numbers to get 9. Return 9.
Input: readings = [-5,8,8,8] Output: 19
byDistance is [-5, 8, 8, 8]. Add its numbers to get 19. Return 19.
Input: readings = [] Output: 0
byDistance is []. Add its numbers to get 0. Return 0.
Input limits
- 0 <= input size <= 64.
- Answers fit in a signed 32-bit integer: -2,147,483,648 through 2,147,483,647.
- Input numbers have no decimal part. They range from -1,000,000 to 1,000,000. Follow any extra input rules in task 1.
Efficiency goal
Big-O describes how the work or memory needed grows as the input gets larger.
Efficiency goal: time O(n log n); extra memory, including the helper list, O(n). n is the input length. These labels describe how work and memory grow with the input.
Practice focus
Build byDistance first, then return exactly what the tasks ask for. Follow the order, keep repeated values when the rule says so, and check the empty case.