1. Sorted List Insertion with Binary Search
Intuition
Maintain a sorted dynamic array nums.
For each incoming element x in instructions:
1. Use binary search (lower_bound) to find the count of elements strictly smaller than x.
2. Use binary search (upper_bound) to find the count of elements <= x. The count of elements strictly greater than x is \text{nums.size()} - \text{upper\_bound}.
3. Add min(\text{strictly less}, \text{strictly greater}) to total cost.
4. Insert x into nums at the upper_bound position.
Even though binary search takes O(log n), inserting into a dynamic array requires shifting elements in O(n) time, leading to O(n2) overall time complexity.
When to apply: Constraint sizes where n <= 2000.
Algorithm
- Step 1: Initialize sorted list nums = [] and totalCost = 0.
- Step 2: For each x in instructions, compute strictly less count using lower_bound.
- Step 3: Compute strictly greater count as nums.size() - upper_bound.
- Step 4: Add min(less, greater) to totalCost modulo 109 + 7.
- Step 5: Insert x into nums maintaining sorted order.
- Step 6: Return totalCost.
#include <iostream>#include <vector>#include <algorithm> int createSortedArrayBrute(const std::vector<int>& instructions) { const int MOD = 1e9 + 7; std::vector<int> nums; long long totalCost = 0; for (int x : instructions) { auto itLow = std::lower_bound(nums.begin(), nums.end(), x); auto itHigh = std::upper_bound(nums.begin(), nums.end(), x); int less = itLow - nums.begin(); int greater = nums.end() - itHigh; totalCost = (totalCost + std::min(less, greater)) % MOD; nums.insert(itHigh, x); } return totalCost;} int main() { std::vector<int> inst = {1, 5, 6, 2}; std::cout << createSortedArrayBrute(inst) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(n^2) due to array element shifts on insertion - Space complexity:
O(n) auxiliary space for nums list