Skip to content

Commit 5ae7247

Browse files
authored
Update 125-Valid-Palindrome.js
The first solution seems to be O(n^2) since there is a nested loop in the isValid function. I have added a second O(n) solution in both time and space complexity.
1 parent ad607dc commit 5ae7247

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

javascript/125-Valid-Palindrome.js

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/**
22
* https://leetcode.com/problems/valid-palindrome/
3-
* Time O(N) | Space O(1)
3+
* Time O(N^2) | Space O(1)
44
* @param {string} s
55
* @return {boolean}
66
*/
@@ -35,3 +35,20 @@ const isNonAlphaNumeric = (char) => {
3535

3636
return isNonAlpha && isNonNumeric;
3737
};
38+
39+
/**
40+
* https://leetcode.com/problems/valid-palindrome/
41+
* Time O(N) | Space O(N)
42+
* @param {string} s
43+
* @return {boolean}
44+
*/
45+
var isPalindrome = function(s) {
46+
if (!s.length) return true;
47+
48+
s = s.toLowerCase();
49+
s = s.replace(/[^a-z0-9]/gi, '');
50+
51+
let reversed = s.split('').reverse().join('');
52+
53+
return reversed === s;
54+
};

0 commit comments

Comments
 (0)