✅ | TOP 99% | O(0) | BEAST MODE |  PYTHON 4 | ✅
IntuitionApproachComplexity
Time complexity:

Space complexity:
Code
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->

# Approach
<!-- Describe your approach to solving the problem. -->

# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```python3 []
class Solution:
    def sumImbalanceNumbers(self, nums: List[int]) -> int:
        seen = {
            nums[0]: 0
        }

        n = 0
        prev_imbalance_sum = 0
        iterator = enumerate(nums)
        next(iterator)
        for i, x in iterator:
            # suppose u add a value x to a ls
            # consider all subarrays ending at the prev index
            # for each subarray ending at this prev index:
            # if x in ls: its imbalance number stays the same
            # if x + 1 in ls and x - 1 in ls: imbalance number goes down by 1
            # if x + 1 in ls: in stays same
            # if x - 1 in ls: in stays same
            # by default: add one per subarray ending at i
            # for each subarray ending at i, starting at j (for j from 0 to i - 1):
            # - 0 if seen.get(x, -1) >= j
            # otherwise:
            # - default +1
            # - (-1) if seen.get(x + 1, -1) >= j
            # - (-1) if seen.get(x - 1, -1) >= j

            # prev_x_idx = seen.get(x, -1)
            # update = i - (prev_x_idx + 1)
            # x_next_idx = seen.get(x + 1, -1)
            # x_prev_idx = seen.get(x - 1, -1)
            # if x_next_idx > prev_x_idx:
            #     update -= (x_next_idx + 1) - (prev_x_idx + 1)
            # if x_prev_idx > prev_x_idx:
            #     update -= (x_prev_idx + 1) - (prev_x_idx + 1)
            prev_x_idx = seen.get(x, -1)
            update = i - (prev_x_idx + 1)
            x_next_idx = seen.get(x + 1, -1)
            x_prev_idx = seen.get(x - 1, -1)
            if x_next_idx > prev_x_idx:
                update -= x_next_idx - prev_x_idx
            if x_prev_idx > prev_x_idx:
                update -= x_prev_idx - prev_x_idx

            this_imbalance_sum = prev_imbalance_sum + update
            prev_imbalance_sum = this_imbalance_sum

            n = n + this_imbalance_sum

            seen[x] = i

        return n



```
['Python3']