Skip to content

Commit 7fb5baa

Browse files
committed
Added Logarithmic time complexity.
Optimised palindrome to Big(O) of Log N.
1 parent 52f8bb8 commit 7fb5baa

File tree

2 files changed

+26
-17
lines changed

2 files changed

+26
-17
lines changed

palindrome/index.js

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,19 @@ const palindrome = (str) => {
4141
// }
4242
// return true;
4343

44-
// Naive algorithm.
4544
// Big(O) = log N
4645
// Multiple pointers pattern with every() array function
47-
return str.split('').every((char, i) => char === str[str.length - i - 1]);
46+
// return str.split('').every((char, i) => char === str[str.length - i - 1]);
47+
48+
// Big(O) = log N
49+
if (str.length === 0) return false;
50+
let i = 0;
51+
let j = Math.floor((str.length) / 2);
52+
while(i < j) {
53+
if(str[j] !== str[str.length - j - 1]) return false;
54+
j--;
55+
}
56+
return true;
4857
};
4958

5059
module.exports = palindrome;

palindrome/test.js

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -20,18 +20,18 @@ test(`Palindrome '' to give undefined`, () => {
2020
expect(palindrome('')).toEqual(undefined);
2121
});
2222

23-
test('minAdjacentSwap is a function', () => {
24-
expect(typeof minAdjacentSwap).toEqual('function');
25-
});
26-
test('minAdjacentSwap mamad to give 3', () => {
27-
expect(minAdjacentSwap('mamad')).toEqual(3);
28-
});
29-
test('minAdjacentSwap asflkj to give -1', () => {
30-
expect(minAdjacentSwap('asflkj')).toEqual(-1);
31-
});
32-
test('minAdjacentSwap aabb to give 2', () => {
33-
expect(minAdjacentSwap('aabb')).toEqual(2);
34-
});
35-
test(`minAdjacentSwap ntiin to give 1`, () => {
36-
expect(minAdjacentSwap('ntiin')).toEqual(1);
37-
});
23+
// test('minAdjacentSwap is a function', () => {
24+
// expect(typeof minAdjacentSwap).toEqual('function');
25+
// });
26+
// test('minAdjacentSwap mamad to give 3', () => {
27+
// expect(minAdjacentSwap('mamad')).toEqual(3);
28+
// });
29+
// test('minAdjacentSwap asflkj to give -1', () => {
30+
// expect(minAdjacentSwap('asflkj')).toEqual(-1);
31+
// });
32+
// test('minAdjacentSwap aabb to give 2', () => {
33+
// expect(minAdjacentSwap('aabb')).toEqual(2);
34+
// });
35+
// test(`minAdjacentSwap ntiin to give 1`, () => {
36+
// expect(minAdjacentSwap('ntiin')).toEqual(1);
37+
// });

0 commit comments

Comments
 (0)