#1649

Create Sorted Array through Instructions

Hard
ArrayBinary SearchDivide and ConquerBinary Indexed TreeSegment TreeMerge SortOrdered SetBinary Indexed TreeSegment TreeCounting Inversions
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(n)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

Using a Binary Indexed Tree (BIT) allows us to efficiently count the number of elements less than and greater than the current element in logarithmic time, significantly speeding up the process.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a Binary Indexed Tree (BIT) to keep track of counts of elements.
  2. 2Step 2: For each element in instructions, use BIT to find the count of elements less than and greater than the current element.
  3. 3Step 3: Calculate the cost as the minimum of these two counts and add it to total_cost.
  4. 4Step 4: Update the BIT with the current element to include it in future counts.
  5. 5Step 5: Return total_cost after processing all elements.
solution.py29 lines
1# Full working Python code
2
3class BIT:
4    def __init__(self, size):
5        self.size = size
6        self.tree = [0] * (size + 1)
7
8    def update(self, index, value):
9        while index <= self.size:
10            self.tree[index] += value
11            index += index & -index
12
13    def query(self, index):
14        total = 0
15        while index > 0:
16            total += self.tree[index]
17            index -= index & -index
18        return total
19
20def createSortedArray(instructions):
21    max_val = max(instructions)
22    bit = BIT(max_val)
23    total_cost = 0
24    for instruction in instructions:
25        less_count = bit.query(instruction - 1)
26        greater_count = len(instructions) - bit.query(instruction)
27        total_cost += min(less_count, greater_count)
28        bit.update(instruction, 1)
29    return total_cost % (10**9 + 7)

Complexity note: The complexity is reduced to O(n log n) because each insertion and query operation in the BIT takes logarithmic time, making it efficient for large inputs.

  • 1Using data structures like BIT can significantly reduce the time complexity of counting operations.
  • 2Understanding how to maintain sorted order efficiently is crucial for problems involving dynamic arrays.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.