Skip to content

Commit 44bcbef

Browse files
author
Mauricio Klein
committed
Add solution for challenge #62
1 parent b28de27 commit 44bcbef

File tree

6 files changed

+65
-0
lines changed

6 files changed

+65
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -61,3 +61,4 @@
6161
- [x] [Challenge 59: Sort Colors](challenge-59/)
6262
- [x] [Challenge 60: Group anagrams](challenge-60/)
6363
- [x] [Challenge 61: Full Binary Tree](challenge-61/)
64+
- [x] [Challenge 62: Palindrome with maximum "k" deletions](challenge-62/)

challenge-62/Makefile

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
test:
2+
python test_*.py
3+
4+
.PHONY: test

challenge-62/README.md

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Palindrome with maximum "k" deletions
2+
3+
This problem was asked by Google.
4+
5+
## Description
6+
7+
Given a string which we can delete at most k, return whether you can make a palindrome.
8+
9+
## Example
10+
11+
```
12+
Input:
13+
word = "waterrfetawx"
14+
k = 2
15+
16+
Output: True # Deleting "f" and "x" gives us a palindrome
17+
```

challenge-62/__init__.py

Whitespace-only changes.

challenge-62/solver.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""
2+
Time complexity: O(2^min(n,k)) (where n = length of the word)
3+
Space complexity: O(2^min(n,k)) (for the call stack)
4+
"""
5+
def has_palindrome(word, k):
6+
return helper(word, k, 0, len(word)-1)
7+
8+
def helper(word, k, left, right):
9+
while left < right:
10+
if word[left] != word[right]:
11+
""" No more removals left: not a solution """
12+
if k == 0:
13+
return False
14+
15+
"""
16+
Recurse...
17+
- Removing the left most char (l)
18+
- Removing the right most char (r)
19+
"""
20+
l = helper(word, k - 1, left + 1, right )
21+
r = helper(word, k - 1, left , right - 1)
22+
23+
return l or r
24+
25+
left += 1
26+
right -= 1
27+
28+
""" Found a palindrome """
29+
return True

challenge-62/test_solver.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import unittest
2+
from solver import has_palindrome
3+
4+
class TestSolver(unittest.TestCase):
5+
def test_has_palindrome(self):
6+
self.assertTrue (has_palindrome("waterrfetawx", 2))
7+
self.assertTrue (has_palindrome("waterrfetawx", 3))
8+
self.assertFalse(has_palindrome("waterrfetawx", 1))
9+
self.assertTrue (has_palindrome("waterretaw" , 0))
10+
self.assertTrue (has_palindrome("yyyyaxxxx" , 8))
11+
self.assertTrue (has_palindrome("yyyyxxxx" , 8))
12+
13+
if __name__ == "__main__":
14+
unittest.main()

0 commit comments

Comments
 (0)