-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem-3_Check_for_Palindrome.js
More file actions
60 lines (52 loc) · 2.17 KB
/
Problem-3_Check_for_Palindrome.js
File metadata and controls
60 lines (52 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Problem-3_Check_for_Palindrome with Solution, Explanation, Verification, and Execution:
// To check for palindrome, we can implement the Solution like below:
// -------------------------------------------------------------------
function isPalindrome(word) {
let left = 0;
let right = word.length - 1;
while (left < right) {
if (word[left].toLowerCase() !== word[right].toLowerCase()) {
return false;
}
left++;
right--;
}
return true;
}
// Explanation:
// ---------------
// This function uses two pointers: one starting at the beginning (left) and one at the end (right) of the string. It enters a while loop that continues as long as the pointers have not crossed each other. In each iteration, it compares the characters at the pointers (converted to lowercase for case-insensitivity); if they differ, it returns false. Otherwise, it moves the left pointer forward and the right backward. If the loop completes without mismatches, it returns true. This two-pointer technique efficiently checks symmetry without creating a reversed copy.
// Verification:
// ----------------
// Example-1:
// function isPalindrome(madam) {
// let left = 0;
// let right = madam.length - 1;
// while (left < right) {
// if (madam[left].toLowerCase() !== madam[right].toLowerCase()) {
// return false;
// }
// left++;
// right--;
// }
// return true;
// }
// console.log(isPalindrome("madam"));
// Example-2:
// function isPalindrome(hello) {
// let left = 0;
// let right = hello.length - 1;
// while (left < right) {
// if (hello[left].toLowerCase() !== hello[right].toLowerCase()) {
// return false;
// }
// left++;
// right--;
// }
// return true;
// }
// console.log(isPalindrome("hello"));
// Execution of the above code block in IDE environment with node.js installed:
// ----------------------------------------------------------------------
// Input (In the directory in IDE environment with node.js installed): 'node Problem-3_Check_for_Palindrome.js'
// Output (In the directory in IDE environment with node.js installed): '3'