# 315 Count of Smaller Numbers After Self

You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts\[i] is the number of smaller elements to the right of nums\[i].

Example:

```
Given nums = [5, 2, 6, 1]

To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.
Return the array [2, 1, 1, 0].
```

## Naive Implementation

**The Idea:** First I built an array the returns the index for the next smallest element in the array. Then iterating from the end, iterate to count the number of smallest elements beginning from the next smallest element.

**Complexity:** O(n + n^2) time and O(n) space

```python
class Solution:
    def countSmaller(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """

        def next_smallest_element(nums):
            stack = []
            next_smallest = [-1] * len(nums)

            for i, num in enumerate(nums, 0):
                while stack and stack[-1][1] > num:
                    next_smallest[stack[-1][0]] = i
                    stack.pop()
                stack.append((i, num))
            return next_smallest

        def count_num_smallested(start, ref):
            count = 0
            for i in range(start, len(nums)):
                if nums[i] < ref:
                    count += 1
            return count

        next_smallest = next_smallest_element(nums)
        count_smaller = [0] * len(nums)
        for i in range(len(nums) - 2, -1, -1):
            if next_smallest[i] != -1:
                count_smaller[i] = count_num_smallested(next_smallest[i], nums[i])
        return count_smaller
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/315-count-of-smaller-numbers-after-self.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
