githubEdit

14. Police and Thieves

βœ… GFG solution for the Police and Thieves problem using an optimized two pointers greedy approach to maximize caught thieves. πŸš€

The problem can be found at the following link: πŸ”— Question Linkarrow-up-right

🧩 Problem Description

Given an array arr[], where each element contains either a 'P' for policeman or a 'T' for thief. Find the maximum number of thieves that can be caught by the police.

Keep in mind the following conditions:

  • Each policeman can catch only one thief.

  • A policeman cannot catch a thief who is more than k units away from him.

πŸ“˜ Examples

Example 1

Input: arr[] = ['P', 'T', 'T', 'P', 'T'], k = 1
Output: 2
Explanation: Maximum 2 thieves can be caught. First policeman catches first thief and second 
policeman can catch either second or third thief.

Example 2

Input: arr[] = ['T', 'T', 'P', 'P', 'T', 'P'], k = 2
Output: 3
Explanation: Maximum 3 thieves can be caught.

πŸ”’ Constraints

  • $1 \le \text{arr.size()} \le 10^5$

  • $1 \le k \le 1000$

  • $\text{arr}[i] = \text{'P'}$ or $\text{'T'}$

βœ… My Approach

The optimal approach uses the Two Pointers technique to efficiently match police and thieves within the allowed distance:

Two Pointers Strategy

  1. Initialize Pointers:

    • Use two pointers: p for tracking policemen positions and t for tracking thief positions.

    • Both pointers start at index 0.

    • Maintain a counter cnt to track successful catches.

  2. Find Next Available Positions:

    • Advance pointer p until it finds a policeman ('P').

    • Advance pointer t until it finds a thief ('T').

  3. Check Matching Condition:

    • If both pointers are valid (within bounds) and the distance between them is ≀ k:

      • Increment the catch counter.

      • Move both pointers forward (match made).

    • If thief is before policeman but out of range, advance thief pointer.

    • If policeman is before thief but out of range, advance policeman pointer.

  4. Continue Until Exhausted:

    • Repeat until either all police or all thieves have been processed.

    • Return the total count of successful catches.

πŸ“ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n), where n is the size of the array. Each element is visited at most once by either the police pointer or the thief pointer, resulting in a linear scan through the array.

  • Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for the pointers and counter variables, regardless of the input size.

πŸ§‘β€πŸ’» Code (C++)

chevron-right⚑ View Alternative Approaches with Code and Analysishashtag

πŸ“Š 2️⃣ Separate Lists Approach

πŸ’‘ Algorithm Steps:

  1. Store all police and thief positions in separate lists.

  2. Use two pointers on both lists to find matching pairs.

  3. Match each policeman with closest thief within distance k.

  4. Advance pointers intelligently based on distance criteria.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n) - Linear scan plus linear matching

  • Auxiliary Space: πŸ’Ύ O(n) - Additional space for position lists

βœ… Why This Approach?

  • Clear separation of concerns with distinct lists

  • Easy to understand matching logic

  • Good for interview explanations

πŸ“Š 3️⃣ Queue-Based Approach

πŸ’‘ Algorithm Steps:

  1. Use queues to store positions of police and thieves.

  2. Process pairs from front of queues sequentially.

  3. Match based on distance constraint k.

  4. Remove matched pairs and advance appropriately.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n) - Linear processing with queue operations

  • Auxiliary Space: πŸ’Ύ O(n) - Queue storage for positions

βœ… Why This Approach?

  • Queue naturally maintains order for sequential matching

  • Simple logic for processing pairs

  • Useful pattern for similar problems

πŸ†š πŸ” Comparison of Approaches

πŸš€ Approach

⏱️ Time Complexity

πŸ’Ύ Space Complexity

βœ… Pros

⚠️ Cons

🏷️ Two Pointers

🟒 O(n)

🟒 O(1)

πŸš€ Optimal time & space

πŸ”§ Requires careful pointer logic

πŸ“Š Separate Lists

🟒 O(n)

🟑 O(n)

πŸ“– Clear and readable

πŸ’Ύ Extra space needed

πŸ”„ Queue-Based

🟒 O(n)

🟑 O(n)

⚑ Natural FIFO processing

πŸ’Ύ Additional queue overhead

πŸ† Best Choice Recommendation

🎯 Scenario

πŸŽ–οΈ Recommended Approach

πŸ”₯ Performance Rating

πŸ… Optimal performance needed

πŸ₯‡ Two Pointers

β˜…β˜…β˜…β˜…β˜…

πŸ“– Readability priority

πŸ₯ˆ Separate Lists

β˜…β˜…β˜…β˜…β˜†

πŸ”§ Sequential processing

πŸ₯‰ Queue-Based

β˜…β˜…β˜…β˜…β˜†

πŸ§‘β€πŸ’» 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