diff --git a/README.md b/README.md index cd3e466..5b3b748 100644 --- a/README.md +++ b/README.md @@ -78,4 +78,6 @@ - [Task #6](src/neetcode/arrays-&-hashing/encode-and-decode-strings) - _Encode And Decode Strings_ - _[check the task](https://neetcode.io/problems/string-encode-and-decode)_ - [Task #7](src/neetcode/arrays-&-hashing/product-of-array-except-self) - _Products of Array Except Self_ - _[check the task](https://neetcode.io/problems/products-of-array-discluding-self)_ - [Task #8](src/neetcode/arrays-&-hashing/valid-sudoku) - _Valid Sudoku_ - _[check the task](https://neetcode.io/problems/valid-sudoku)_ - - [Task #9](src/neetcode/arrays-&-hashing/longest-consecutive-sequence) - _Longest Consecutive Sequence_ - _[check the task](https://neetcode.io/problems/longest-consecutive-sequence)_ \ No newline at end of file + - [Task #9](src/neetcode/arrays-&-hashing/longest-consecutive-sequence) - _Longest Consecutive Sequence_ - _[check the task](https://neetcode.io/problems/longest-consecutive-sequence)_ +- Two Pointers + - [Task #10](src/neetcode/two-pointers/valid-palindrome) - _Valid Palindrome_ - _[check the task](https://neetcode.io/problems/is-palindrome)_ \ No newline at end of file diff --git a/src/neetcode/two-pointers/valid-palindrome/solution.test.ts b/src/neetcode/two-pointers/valid-palindrome/solution.test.ts new file mode 100644 index 0000000..84a2879 --- /dev/null +++ b/src/neetcode/two-pointers/valid-palindrome/solution.test.ts @@ -0,0 +1,13 @@ +import { isPalindrome } from './solution'; + +describe('Valid Palindrome | NeetCode RoadMap | Testcases', () => { + test('#1 Valid string', () => { + const s = 'Was it a car or a cat I saw?'; + expect(isPalindrome(s)).toBe(true); + }); + + test('#2 Invalid string', () => { + const s = 'tab a cat'; + expect(isPalindrome(s)).toBe(false); + }); +}); diff --git a/src/neetcode/two-pointers/valid-palindrome/solution.ts b/src/neetcode/two-pointers/valid-palindrome/solution.ts new file mode 100644 index 0000000..2f1ca44 --- /dev/null +++ b/src/neetcode/two-pointers/valid-palindrome/solution.ts @@ -0,0 +1,25 @@ +/** + * @param {string} s - input string + * @return {boolean} `true` if `s` is a palindrome, false otherwise + */ +export const isPalindrome = (s: string): boolean => { + const isAlphaNumeric = (char: string): boolean => + (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || (char >= '0' && char <= '9'); + + let right = s.length - 1; + let left = 0; + while (left < right) { + while (left < right && !isAlphaNumeric(s[left])) { + left++; + } + while (left < right && !isAlphaNumeric(s[right])) { + right--; + } + if (s[left].toLowerCase() !== s[right].toLowerCase()) { + return false; + } + left++; + right--; + } + return true; +};