O(n) solution
Complexity\n- Time complexity:\nO(n) (assuming unordered_map)\n- Space complexity:\nO(n)\n\n# Code\n\nclass Solution:\n    def sumImbalanceNumbers(self, nums: L
# Complexity\n- Time complexity:\nO(n) (assuming unordered_map)\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n    def sumImbalanceNumbers(self, nums: List[int]) -> int:\n        ### Add first 2 nums to map, check for gap\n        indices = {}\n        total = 0\n        prev = 0\n        indices[nums[0]] = 0\n        for i in range(1, len(nums)):\n            curSum = prev\n            below_index = indices[nums[i]-1] if nums[i]-1 in indices else -1\n            above_index = indices[nums[i]+1] if nums[i]+1 in indices else -1\n            cur_index = indices[nums[i]] if nums[i] in indices else -1\n            soonest_zero_imbalance = max(max(below_index, above_index), cur_index)\n            if soonest_zero_imbalance == -1:\n                curSum += i\n            else:\n                curSum += i - soonest_zero_imbalance - 1\n            if below_index != -1 and above_index != -1 and min(below_index, above_index) > cur_index:\n                curSum -= min(below_index, above_index) + 1\n                if cur_index != -1:\n                    curSum += cur_index + 1\n            total += curSum\n            prev = curSum \n            indices[nums[i]] = i\n        return total\n```
['Python3']