Sunday, February 20, 2022

Leet Code 1944. Number of Visible People in a Queue

I/p: [10,6,8,5,11,9]

O/p: [3,1,2,1,1,0] 

https://leetcode.com/problems/number-of-visible-people-in-a-queue/ 





package pep.Day26;

import java.util.Stack;

public class LeetCode_1944_Number_of_Visible_People_in_Queue {
public static void main(String[] args) {
int[] arr = {10, 6, 8, 5, 11, 9};
for (int x : canSeePersonsCount(arr)) {
System.out.print(x + "\t");
}
}

public static int[] canSeePersonsCount(int[] heights) {
int n = heights.length;

int[] ans = new int[n];
Stack<Integer> stack = new Stack<>();

for (int i = n - 1; i >= 0; i--) {
int count = 0;
// jab tak stack ki peek pr element chota hai, pop kr do
// reason: koi bhi banda, mere current height wale bande,
// se choti height wale ko nhi dekh skta, woh shadow me chip jaega
while (!stack.isEmpty() && stack.peek() <= heights[i]) {
count++;
stack.pop();
}

// agr stack.peek pr bada element hai to, count increase kr do
if (!stack.isEmpty() && stack.peek() > heights[i])
count++;

ans[i] = count;
stack.push(heights[i]);
}

return ans;
}
}



No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...