LeetCode 1944: Number of Visible People in a Queue Solution
Master LeetCode problem 1944 (Number of Visible People in a Queue), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1944. Number of Visible People in a Queue
Problem Explanation
Explanation:
To solve this problem, we can use a monotonic decreasing stack to keep track of the visible people in the queue. We iterate through the queue from right to left and maintain a stack of indices. For each person, we pop elements from the stack until we find a person taller than the current person or the stack becomes empty. The number of visible people for the current person is the difference between the current index and the top of the stack. Finally, we push the current index onto the stack.
Time Complexity: O(n) where n is the number of people in the queue. Space Complexity: O(n) where n is the number of people in the queue.
Solution Code
class Solution {
public int[] canSeePersonsCount(int[] heights) {
int n = heights.length;
int[] result = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = n - 1; i >= 0; i--) {
while (!stack.isEmpty() && heights[i] > heights[stack.peek()]) {
result[i] += 1 + result[stack.pop()];
}
if (!stack.isEmpty()) {
result[i]++;
}
stack.push(i);
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1944 (Number of Visible People in a Queue)?
This page provides optimized solutions for LeetCode problem 1944 (Number of Visible People in a Queue) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1944 (Number of Visible People in a Queue)?
The time complexity for LeetCode 1944 (Number of Visible People in a Queue) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1944 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1944 in Java, C++, or Python.