Delete Integers In Ascending Order - Google Top Interview Questions


Problem Statement :


You are given a list of unique integers nums and want to delete each number in ascending order.

Return the indices of numbers in order of their deletion.

Constraints

n ≤ 100,000 where n is the length of nums

Example 1

Input

nums = [3, 5, 1, 4, 2]

Output

[2, 3, 0, 1, 0]

Explanation
We delete the numbers in this order:



Delete 1 at index 2 and now we have [3, 5, 4, 2]

Delete 2 at index 3 and now we have [3, 5, 4]

Delete 3 at index 0 and now we have [5, 4]

Delete 4 at index 1 and now we have [5]

Delete 5 at index 0 and now we have []



Solution :



title-img




                        Solution in C++ :

const int SZ = 1 << 17;
void upd(vector<int>& tree, int idx, int val) {
    idx += SZ;
    while (idx) {
        tree[idx] += val;
        idx /= 2;
    }
}
int qry(vector<int>& tree, int lhs, int rhs) {
    lhs += SZ;
    rhs += SZ;
    int ret = 0;
    while (lhs <= rhs) {
        if (lhs % 2) ret += tree[lhs++];
        if (rhs % 2 == 0) ret += tree[rhs--];
        lhs /= 2;
        rhs /= 2;
    }
    return ret;
}
vector<int> solve(vector<int>& nums) {
    vector<int> tree(2 * SZ);
    int n = nums.size();
    vector<int> ret;
    vector<pair<int, int>> pairs;
    for (int i = 0; i < n; i++) pairs.emplace_back(nums[i], i);
    sort(pairs.begin(), pairs.end());
    for (auto p : pairs) {
        ret.push_back(p.second - qry(tree, 0, p.second - 1));
        upd(tree, p.second, 1);
    }
    return ret;
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    class SegTree {
        int leftMost, rightMost, sum;
        SegTree left, right;
        int[] a;

        public SegTree(int[] a, int leftMost, int rightMost) {
            this.a = a;
            this.leftMost = leftMost;
            this.rightMost = rightMost;
            int mid = (rightMost + leftMost) / 2;
            if (leftMost == rightMost) {
                sum = a[leftMost];
            } else {
                left = new SegTree(a, leftMost, mid);
                right = new SegTree(a, mid + 1, rightMost);
                recalc();
            }
        }

        void recalc() {
            if (leftMost == rightMost)
                return;
            sum = right.sum + left.sum;
        }

        void pointUpdate(int index, int newVal) {
            if (leftMost == rightMost) {
                sum = newVal;
                return;
            }
            if (index <= left.rightMost)
                left.pointUpdate(index, newVal);
            else
                right.pointUpdate(index, newVal);
            recalc();
        }

        int rangeSum(int l, int r) {
            // three cases:
            // 1. no intersect
            if (r < leftMost || rightMost < l)
                return 0;
            // 2. partially contained
            if (l <= leftMost && r >= rightMost)
                return sum;
            // 3. don't know
            return left.rangeSum(l, r) + right.rangeSum(l, r);
        }
    }

    int[] solve(int[] nums) {
        List<int[]> ls = new ArrayList<>();
        int[] res = new int[nums.length];
        if (nums.length == 0)
            return res;
        for (int i = 0; i < nums.length; i++) {
            ls.add(new int[] {nums[i], i});
        }

        Collections.sort(ls, (a, b) -> a[0] - b[0]);

        SegTree segTree = new SegTree(new int[nums.length], 0, nums.length - 1);
        for (int i = 0; i < nums.length; i++) {
            int[] n = ls.get(i);
            int index = n[1];
            int rangeSum = segTree.rangeSum(0, index);
            res[i] = index - rangeSum;
            segTree.pointUpdate(index, 1);
        }
        return res;
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def solve(self, nums):
        # indices holds pairs (index, number)
        indices = list(enumerate(nums))
        indices.sort(key=lambda x: -x[1])
        sl = SortedList()
        result = []
        for idx, _ in indices:
            t = sl.bisect_left(idx)
            result.append(t)
            sl.add(idx)

        return result[::-1]
                    


View More Similar Problems

Waiter

You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the

View Solution →

Queue using Two Stacks

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que

View Solution →

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →

Down to Zero II

You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.

View Solution →

Truck Tour

Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N-1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump. Initially, you have a tank of infinite capacity carrying no petr

View Solution →

Queries with Fixed Length

Consider an -integer sequence, . We perform a query on by using an integer, , to calculate the result of the following expression: In other words, if we let , then you need to calculate . Given and queries, return a list of answers to each query. Example The first query uses all of the subarrays of length : . The maxima of the subarrays are . The minimum of these is . The secon

View Solution →