Review of the Code

This page shows the strategy behind the code, as well as the analyis of space and time efficiency.

Explanation:
Code:

The function palindrome accepts a string from the user and returns true if it is a palindrome or false if it is not. The user input is the value of the string and the spanE element targets the html element in charge of conveying the result to the user.

Before the loop, the j variable points to the last index of the string. In the for loop, we compare values of the first half of the string with values in the second half, which is the purpose of decrementing the j variable after every iteration. If at any time the i and j pairs do not match, then clearly the word does not respect the mirror-like quality of a palindrome. If there is no mismatch, then the word is a palindrome.

In terms of space, there is no extra data structure being used except the j variable which is simply O(1) space. With regards to time-complexity, a single loop is done across the string, which is just O(n) time. This algorithm is therefore efficient.

function palindrome(str) {
                let spanE = document.getElementById("palinAnswer");

                if (myTrim(str) == "") {
                  spanE.innerHTML = "Please put in letters!";
                  return false;
                }
          
                j = str.length - 1;
          
                for (let i = 0; i < str.length; i++) {
                  if (str.charAt(i).toLowerCase() != str.charAt(j).toLowerCase()) {
                    spanE.innerHTML = "It's not a palindrome.";
                    return false;
                  }
                  j--;
                }
                spanE.innerHTML = "It's a palindrome!";
                return true;
              }