silentknight00's blog

By silentknight00, history, 6 years ago, In English

Given an array [1,3,4,2] we should get an array [0,0,0,2]. Can someone suggest a quick method for doing this

  • Vote: I like it
  • +1
  • Vote: I do not like it

»
6 years ago, # |
  Vote: I like it 0 Vote: I do not like it

This is essentially the inversion problem which can be solved using segment tree or binary indexes tree in O(nlogn). ( You can search for it online)

»
6 years ago, # |
Rev. 3   Vote: I like it +10 Vote: I do not like it

Iterate from the left and imagine the array is the skyscrapers with height a[i]. Now we want to maintain all skyscrapers visible from i. To do so just maintain a stack. O(n).

stack<int>X;
for (int i = 0; i < n; i++)
{
	while (!X.empty() && a[X.top()] <= a[i])
	{
		X.pop();
	}
	if (X.empty())
		ans[i] = -1;
	else
		ans[i] = X.top();
	X.push(i);
}
  • »
    »
    6 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    But If I input 1 3 5 4, the output is 2. What am I missing?