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 Link
π§© 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
Initialize Pointers:
Use two pointers:
pfor tracking policemen positions andtfor tracking thief positions.Both pointers start at index 0.
Maintain a counter
cntto track successful catches.
Find Next Available Positions:
Advance pointer
puntil it finds a policeman ('P').Advance pointer
tuntil it finds a thief ('T').
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.
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++)
π§βπ» 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