Back to course home
0% completed
Vote For New Content
Python Solution using less space and saving one iteration than what's presented as the right solution
Leopoldo Hernandez
Feb 5, 2024
""" My solution: Time Complexity: The time complexity is O(n), where n is the length of the input list nums. The function iterates through the list twice: once to calculate the total sum (total), and once to calculate the difference array. Space Complexity: The space complexity is O(n). The differenceArray list is of the same length as nums, and additional variables (total, left, right, diff_total, el) use constant space. """ class Solution: def findDifferenceArray(self, nums): n = len(nums) differenceArray = [0] * n total = 0 for el in nums: total += el left = 0 for idx, el in enumerate(nums): left += el right = total - left diff_total = (left - el) - right differenceArray[idx] = diff_total * -1 if diff_total < 0 else diff_total return differenceArray
2
0
Comments
Comments
On this page
Problem Statement
Examples
Solution
Step-by-step Algorithm
Algorithm Walkthrough
Code
Complexity Analysis
Time Complexity
Space Complexity