Skip to content

Commit 17544c5

Browse files
author
Mauricio Klein
committed
Add solution for challenge #49
1 parent 4076784 commit 17544c5

File tree

6 files changed

+77
-0
lines changed

6 files changed

+77
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,4 @@
4848
- [x] [Challenge 46: Sudoku solver](challenge-46/)
4949
- [x] [Challenge 47: Closest coin](challenge-47/)
5050
- [x] [Challenge 48: Median of window](challenge-48/)
51+
- [x] [Challenge 49: Buddy strings](challenge-49/)

challenge-49/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-49/README.md

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Buddy strings
2+
3+
This problem was asked by AirBnB.
4+
5+
## Description
6+
7+
Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B.
8+
9+
## Example
10+
```
11+
Input: A = "ab", B = "ba"
12+
Output: True
13+
14+
Input: A = "ab", B = "ba"
15+
Output: False
16+
17+
Input: A = "aa", B = "aa"
18+
Output: True
19+
20+
Input: A = "aaaaaaabc", B = "aaaaaaacb"
21+
Output: True
22+
23+
Input: A = "", B = "aa"
24+
Output: False
25+
```

challenge-49/__init__.py

Whitespace-only changes.

challenge-49/solver.py

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#
2+
# Time complexity: O(n) (where "n" is the length of any of the strings)
3+
# Space complexity: O(1)
4+
#
5+
def buddy_strings(a, b):
6+
# Check string length match
7+
if len(a) != len(b):
8+
return False
9+
10+
# Check if same string with duplicated characters
11+
if a == b and len(a) > len(set(a)):
12+
return True
13+
14+
# Calculate the diff between the strings
15+
diff_a, diff_b = [], []
16+
for i in range(len(a)):
17+
if a[i] != b[i]:
18+
diff_a.append(a[i])
19+
diff_b.append(b[i])
20+
21+
if len(diff_a) > 2:
22+
return False
23+
24+
# We expect exactly two diffs to make one swap
25+
# So, if the number of diffs is different of two, more or
26+
# less than one swap is needed and, thus, "false"
27+
if len(diff_a) != 2:
28+
return False
29+
30+
# Check if the swaps match
31+
if diff_a[0] != diff_b[1] or diff_a[1] != diff_b[0]:
32+
return False
33+
34+
return True

challenge-49/test_solver.py

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import unittest
2+
from solver import buddy_strings
3+
4+
class TestSolver(unittest.TestCase):
5+
def test_buddy_strings(self):
6+
self.assertEqual(buddy_strings("ab" , "ba" ), True )
7+
self.assertEqual(buddy_strings("ab" , "ab" ), False)
8+
self.assertEqual(buddy_strings("aa" , "aa" ), True )
9+
self.assertEqual(buddy_strings("aaaaaaabc", "aaaaaaacb"), True )
10+
self.assertEqual(buddy_strings("" , "aa" ), False)
11+
12+
if __name__ == "__main__":
13+
unittest.main()

0 commit comments

Comments
 (0)