Search⌘ K

Solution: Help the Policemen Catch the Thieves

Understand how to solve the police and thieves problem by comparing brute force and greedy strategies. Learn to implement an optimized O(n) time complexity solution that efficiently matches police to thieves while minimizing checks.

Solution #1: Brute Force

C++
int policeThief(char policeThiefArray[], int n, int k) {
int result = 0;
bool caught[n];
for (int i = 0; i < n; i++) {
caught[i] = false;
}
for (int i = 0; i < n; i++) {
//check k steps forward
if (policeThiefArray[i] == 'P' && caught[i] == false) {
for (int j = i; j < (j + k) && j < n && caught[i] == false; j++) {
if (policeThiefArray[j] == 'T' && caught[j] == false) {
caught[i] = true;
caught[j] = true;
break;
}
}
}
//check k steps backward
if (policeThiefArray[i] == 'P' && caught[i] == false) {
for (int j = i; j > (j - k) && j > -1 && caught[i] == false; j--) {
if (policeThiefArray[j] == 'T' && caught[j] == false) {
caught[i] = true;
caught[j] = true;
break;
}
}
}
}
for (int i = 0; i < n; i++) {
if (policeThiefArray[i] == 'T' && caught[i] == true) {
result++;
}
}
return result;
}
int main() {
int k, n;
char policeTheifArray[] = {'P', 'T', 'T', 'P', 'T'};
k = 2;
n = sizeof(policeTheifArray) / sizeof(policeTheifArray[0]);
cout << "Maximum thieves caught for {P, T, T, P, T}: " << policeThief(policeTheifArray, n, k) << endl;
char policeTheifArray1[] = {'T', 'T', 'P', 'P', 'T', 'P'};
k = 2;
n = sizeof(policeTheifArray1) / sizeof(policeTheifArray1[0]);
cout << "Maximum thieves caught for {T, T, P, P, T,P}: " << policeThief(policeTheifArray1, n, k) << endl;
return 0;
}

The brute force method takes the first police found and tries to match it with the nearest thief. However, you can see that this method is very lengthy, confusing, and time intensive.

Time Complexity

The time complexity is O(n2)O(n^2) ...