Sponsored
Sponsored
The Binary Indexed Tree (BIT) allows us to efficiently update elements and calculate cumulative frequencies in an iterative manner. In this approach, we traverse the input array from right to left, update the BIT with the index of the current number, and use the BIT to find the count of numbers which are smaller.
Time Complexity: O(n log n), where n is the number of elements in nums. Updating the BIT and querying both take O(log n) time.
Space Complexity: O(n) for the BIT and result array.
1using System;
2using System.Collections.Generic;
3
4class Solution {
5 public class FenwickTree {
6 private int[] tree;
7 public FenwickTree(int size) {
8 tree = new int[size + 1];
9 }
10 public void Update(int index, int value) {
11 while (index < tree.Length) {
12 tree[index] += value;
13 index += index & -index;
14 }
15 }
16 public int Query(int index) {
17 int sum = 0;
18 while (index > 0) {
19 sum += tree[index];
20 index -= index & -index;
21 }
22 return sum;
23 }
24 }
25 public IList<int> CountSmaller(int[] nums) {
26 int offset = 10000;
27 int size = 20001;
28 FenwickTree bit = new FenwickTree(size);
29 int[] result = new int[nums.Length];
30 for (int i = nums.Length - 1; i >= 0; i--) {
31 result[i] = bit.Query(nums[i] + offset);
32 bit.Update(nums[i] + offset + 1, 1);
33 }
34 return result;
35 }
36 static void Main() {
37 Solution solution = new Solution();
38 int[] nums = {5, 2, 6, 1};
39 IList<int> result = solution.CountSmaller(nums);
40 Console.WriteLine(string.Join(" ", result));
41 }
42}This C# code defines a FenwickTree class for handling Binary Indexed Tree operations. The main function maintains an offset to shift negative index values into the positive index space for the BIT. By iterating the array backwards, the code updates the BIT with each number and accumulates counts of smaller numbers to produce a result list.
This approach takes advantage of the divide and conquer strategy combined with a binary search tree (BST). As we process each number from right to left, we insert them into the BST, which allows us to compute the count of elements smaller than the current number efficiently.
Time Complexity: O(n log n) on average, assuming balanced inserts into the BST.
Space Complexity: O(n) for storing BST nodes and result array.
The JavaScript solution employs a constructor-based system for creating node instances to facilitates insertions and queries relative to node positioning. Calculating preSum in tandem with node creation encapsulates the overall method necessary for counting smaller elements. The recursive formation of tree branches holds up under problem constraints.