Problem
Given an integer arraynums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i].
Examples
Constraints
- 1 <= nums.length <= 10^5
- -10^4 <= nums[i] <= 10^4
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 315 with 22 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 315 # by problem number
lcpy gen -s count_smaller_numbers_after_self # by problem name
nums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i].
Input: nums = [5,2,6,1]
Output: [2,1,1,0]
Input: nums = [-1]
Output: [0]
Input: nums = [-1,-1]
Output: [0,0]
class Solution:
# Time: O(n log n)
# Space: O(n)
def count_smaller(self, nums: list[int]) -> list[int]:
counts = [0] * len(nums)
indices = list(range(len(nums)))
def merge_sort(lo: int, hi: int) -> None:
if hi - lo <= 1:
return
mid = (lo + hi) // 2
merge_sort(lo, mid)
merge_sort(mid, hi)
merged: list[int] = []
i, j = lo, mid
while i < mid and j < hi:
if nums[indices[j]] < nums[indices[i]]:
merged.append(indices[j])
j += 1
else:
counts[indices[i]] += j - mid
merged.append(indices[i])
i += 1
while i < mid:
counts[indices[i]] += j - mid
merged.append(indices[i])
i += 1
while j < hi:
merged.append(indices[j])
j += 1
indices[lo:hi] = merged
merge_sort(0, len(nums))
return counts
| Time | Space |
|---|---|
| O(n log n) | O(n) |