Wednesday, November 30, 2022

[Flipkart][LeetCode] Number of Visible People in a Queue

Problem: There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the ith person.

A person can see another person to their right in the queue if everybody in between is shorter than both of them. More formally, the ith person can see the jth person if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1]).

Return an array answer of length n where answer[i] is the number of people the ith person can see to their right in the queue.

Example:

Input: heights = [10,6,8,5,11,9]
Output: [3,1,2,1,1,0]
Explanation:
Person 0 can see person 1, 2, and 4.
Person 1 can see person 2.
Person 2 can see person 3 and 4.
Person 3 can see person 4.
Person 4 can see person 5.
Person 5 can see no one since nobody is to the right of them.
Input: heights = [5,1,2,3,10]
Output: [4,1,1,1,0]


Approach: We maintain a stack in descending order. We iterate through every element of the input array and check with the top of the stack say 'a', if we found current element is greater than 'a' then we can safely say that 'a' can see current element so we increase the number of element 'a' can see but as we can see that current element greater than 'a', 'a' can't see beyond current element so we can safely pop the top of the stack.


Implementation in C#:

    public int[] CanSeePersonsCount(int[] heights) 

    {

        int length = heights.Length;

        int[] result = new int[length];

        Stack<int> stack = new Stack<int>();

        for (int i = 0; i < length; ++i)

        {

            while (stack.Count > 0 && heights[i] > heights[stack.Peek()])

            {

                ++result[stack.Pop()];

            }

            if (stack.Count > 0)

            {

                ++result[stack.Peek()];

            }

            stack.Push(i);

        }

        return result;

    }


Complexity: O(n)

No comments:

Post a Comment