# Given a string which we can delete at most k, return whether you can make a palindrome.

By | January 5, 2024

Python:

``````def can_make_palindrome(s, k):
def is_palindrome(sub):
return sub == sub[::-1]

n = len(s)
deletions_needed = n - sum([1 for i, c in enumerate(s) if c != s[n - 1 - i]])

return deletions_needed <= k or is_palindrome(s)

# Example usage:
s_example = "abca"
k_example = 1
result = can_make_palindrome(s_example, k_example)
print(result)``````

JavaScript:

``````function canMakePalindrome(s, k) {
const isPalindrome = (sub) => sub === sub.split('').reverse().join('');

const n = s.length;
const deletionsNeeded = n - [...s].reduce((count, c, i) => (c !== s[n - 1 - i]) ? count + 1 : count, 0);

return deletionsNeeded <= k || isPalindrome(s);
}

// Example usage:
const sExample = "abca";
const kExample = 1;
const result = canMakePalindrome(sExample, kExample);
console.log(result);``````

### Java:

``````public class PalindromeChecker {
public static boolean canMakePalindrome(String s, int k) {
int deletionsNeeded = s.length() - s.chars().mapToObj(c -> (char) c)
.filter(c -> c != s.charAt(s.length() - 1 - s.indexOf(c)))
.count();

return deletionsNeeded <= k || isPalindrome(s);
}

private static boolean isPalindrome(String sub) {
return sub.equals(new StringBuilder(sub).reverse().toString());
}

public static void main(String[] args) {
// Example usage:
String sExample = "abca";
int kExample = 1;
boolean result = canMakePalindrome(sExample, kExample);
System.out.println(result);
}
}``````

These solutions check if a string can be converted into a palindrome by allowing at most `k` deletions. The `is_palindrome` function is used to check if a given substring is a palindrome. The Java solution includes a `main` method for example usage.