githubEdit

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 Linkarrow-up-right

🧩 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

  1. 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 i can see person j, then person i can also see everyone that person j could see.

  2. 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.

  3. Calculate Maximum:

    • For each person at position i, the total visible count is left[i] + right[i] - 1.

    • Subtract 1 to avoid counting the person themselves twice.

    • Return the maximum value across all positions.

  4. 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++)

chevron-right⚑ View Alternative Approaches with Code and Analysishashtag

πŸ“Š 2️⃣ Single Pass with Combined Visibility

πŸ’‘ Algorithm Steps:

  1. Process array from left maintaining monotonic stack for left visibility

  2. Store indices and their visible counts in auxiliary structure

  3. Process from right and combine results on the fly

  4. 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:

  1. Use single visibility array updated bidirectionally

  2. Maintain monotonic decreasing stack with indices only

  3. Accumulate counts directly without separate left/right arrays

  4. 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:

  1. For each person, scan left to count visible people with smaller heights.

  2. For each person, scan right to count visible people with smaller heights.

  3. Stop scanning when a person with equal or greater height is encountered.

  4. 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?arrow-up-right. Let's make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Visitor counter

Last updated