23. Maximum People Visible in a Line
β GFG solution to the Maximum People Visible in a Line problem using monotonic stacks to efficiently count visible people in both directions. π
The problem can be found at the following link:π Question Link
π§© Problem Description
You are given an array arr[], where arr[i] represents the height of the ith person standing in a line.
A person i can see another person j if:
height[j] < height[i]There is no person k standing between them such that
height[k] β₯ height[i]
Each person can see in both directions (front and back).
Your task is to find the maximum number of people that any person can see (including themselves).
π Examples
Example 1
Input: arr[] = [6, 2, 5, 4, 5, 1, 6]
Output: 6
Explanation: Person 1 (height = 6) can see five other people at positions (2, 3, 4, 5, 6)
in addition to himself, i.e., total 6. Person 7 (height = 6) can also see 6 people total.Example 2
π Constraints
$1 \le \text{arr.size()} \le 10^4$
$1 \le \text{arr}[i] \le 10^5$
β
My Approach
The optimal approach uses a Monotonic Stack technique to efficiently compute visibility in both directions:
Monotonic Stack Algorithm
Left Visibility Computation:
Initialize a visibility array
left[]where each person can see themselves (value = 1).Use a monotonic decreasing stack to track indices of people.
For each person at position
i, pop all shorter people from the stack and accumulate their visibility counts.This works because if person
ican see personj, then personican also see everyone that personjcould see.
Right Visibility Computation:
Similarly, initialize a visibility array
right[]with value 1 for each person.Process the array from right to left using the same monotonic stack approach.
Accumulate visibility counts for people shorter than the current person.
Calculate Maximum:
For each person at position
i, the total visible count isleft[i] + right[i] - 1.Subtract 1 to avoid counting the person themselves twice.
Return the maximum value across all positions.
Key Insight:
The monotonic stack ensures we only process each element once in each direction.
When a taller person appears, all shorter people in the stack become invisible to future processing.
The accumulated counts propagate visibility transitively.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the size of the array. Each element is pushed and popped from the stack at most once during each pass (left and right), resulting in linear time complexity overall.
Expected Auxiliary Space Complexity: O(n), as we use two auxiliary arrays of size n to store left and right visibility counts, along with a stack that can hold at most n elements in the worst case.
π§βπ» Code (C++)
β‘ View Alternative Approaches with Code and Analysis
π 2οΈβ£ Single Pass with Combined Visibility
π‘ Algorithm Steps:
Process array from left maintaining monotonic stack for left visibility
Store indices and their visible counts in auxiliary structure
Process from right and combine results on the fly
Track maximum visibility count during traversal
π Complexity Analysis:
Time: β±οΈ O(n) - Two linear passes through array
Auxiliary Space: πΎ O(n) - Stack and visibility array
β
Why This Approach?
Combines computation with result tracking
Uses value-count pairs for clarity
Reduces redundant stack operations
π 3οΈβ£ Optimized Stack with Index Only
π‘ Algorithm Steps:
Use single visibility array updated bidirectionally
Maintain monotonic decreasing stack with indices only
Accumulate counts directly without separate left/right arrays
Find maximum in single final pass
π Complexity Analysis:
Time: β±οΈ O(n) - Linear time with stack operations
Auxiliary Space: πΎ O(n) - Single DP array and stack
β
Why This Approach?
Memory efficient with single array reuse
Cleaner stack management
Direct maximum computation
π 4οΈβ£ Brute Force Approach
π‘ Algorithm Steps:
For each person, scan left to count visible people with smaller heights.
For each person, scan right to count visible people with smaller heights.
Stop scanning when a person with equal or greater height is encountered.
Sum both directions and add 1 for the person themselves.
π Complexity Analysis:
Time: β±οΈ O(nΒ²) - Nested iteration for each position
Auxiliary Space: πΎ O(1) - No extra space needed
β
Why This Approach?
Simplest to understand and implement.
No complex data structures required.
Good for small input sizes.
π π Comparison of Approaches
π Approach
β±οΈ Time Complexity
πΎ Space Complexity
β Pros
β οΈ Cons
π·οΈ Two Array Stack
π’ O(n)
π‘ O(n)
π Clear separation of logic
πΎ Uses two auxiliary arrays
π Combined Visibility
π’ O(n)
π‘ O(n)
π Inline result tracking
π§ Slightly complex pair handling
π Single Array Stack
π’ O(n)
π‘ O(n)
β Memory efficient
π§ Array reuse needs care
π Brute Force
π΄ O(nΒ²)
π’ O(1)
π Simple implementation
π Slow for large inputs
π Best Choice Recommendation
π― Scenario
ποΈ Recommended Approach
π₯ Performance Rating
π Optimal performance needed
π₯ Two Array Stack
β β β β β
π Readability priority
π₯ Combined Visibility
β β β β β
π§ Memory constraints
π₯ Single Array Stack
β β β β β
π― Interview/Competitive
π Two Array Stack
β β β β β
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated