Struggling with repeatedly traversing characters in a string to solve the Palindrome challenge

I am working on a recursive solution for a Palindrome problem, but it seems that my code is only considering the first recursive call instead of the second one which should analyze all characters in the string. I suspect there might be a logical error in my algorithm, but I'm having trouble identifying it. Any guidance would be greatly appreciated. Here's the code snippet:

function isPalindrome(totalChars: number, lastIdx: number, str: string): boolean | undefined {
    console.log(`lastIdx: ${lastIdx}; char: ${str[lastIdx]}`);

    let highIdx = lastIdx;
    const lowIdx = totalChars-1 - highIdx;

    // Base Case: 
    if(totalChars === 0) return true;
    if (lowIdx === highIdx) return true;
    if (lowIdx > highIdx) {
        console.log(`Endpoint reached; STR: ${str}; LOW: ${str[lowIdx]}; high: ${str[highIdx]}`);
        return;
    }

    if(str[lowIdx] === str[highIdx]) {
        console.log(`Loop through idx; STR: ${str}; LOW: ${str[lowIdx]}; high: ${str[highIdx]}`);
        return true;
    }
    else if(str[lowIdx] !== str[highIdx]) return false;


    // Recursive Case:
    return isPalindrome(totalChars, highIdx, str) && isPalindrome(totalChars, highIdx-1, str);
}


// console.log("a is Palindrome: " + isPalindrome("a".length, "a".length-1, "a"));
// console.log("motor is Palindrome: " + isPalindrome("motor".length, "motor".length-1,"motor"));
console.log("rotor is Palindrome: " + isPalindrome("rotor".length, "rotor".length-1,"rotor"));

Answer №1

It seems there are a couple of issues that need to be addressed:

  1. The if...else statement in your code will always result in a return being called, which means the recursive call will never be executed. It's important to note that the condition after the else if will always evaluate to true since it is the negation of the condition from the earlier if statement. Furthermore, you don't want to return immediately if the characters don't match as the remaining characters still need to be checked via the recursive call. Therefore, it's best to remove the if block and only use return when the characters differ.

    Instead of this:

        if(str[lowIdx] === str[highIdx]) 
        {
            return true;
        }
        else if(str[lowIdx] !== str[highIdx]) return false;
    

    Consider using just:

        if(str[lowIdx] !== str[highIdx]) return false;
    
  2. The first recursive call passes the same arguments as the current function execution, leading to infinite recursion. In this case, you don't need to make two recursive calls, so you should remove the first one.

    Instead of this:

    return isPalindrome(totalChars, highIdx, str) && isPalindrome(totalChars, highIdx-1, str);
    

    Consider using:

    return isPalindrome(totalChars, highIdx-1, str);
    
  3. The base case has an issue where return is called without a boolean value. The function should always return a boolean value. In this case, it should be true when all character pairs have been compared, and no single middle character remains (assuming even string size). You can combine this base case with the previous one. Additionally, the initial check for totalChars being zero is redundant.

    Instead of this:

    if (totalChars === 0) return true;
    if (lowIdx === highIdx) return true;
    if (lowIdx > highIdx) {
        return;
    }
    

    Consider using:

    if (lowIdx >= highIdx) return true;
    

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for adjusting the dimensions of a child element to match its parent in Angular 12 with Typescript

I have included the child component in the parent component and I am displaying that child component within a col-md-8. What I want to achieve is to highlight a specific div in the child component with additional text, making it equal in size to the parent ...

Integrate Angular 2 components into WebStorm

I am currently working on a project using Angular 2 (rc5) and TypeScript (1.8.10). Angular 2 is built with TypeScript, but in the node_modules directory, I notice that there are JavaScript files (*.js) along with declaration files (*.d.ts). It makes it di ...

obtaining information from newly added form elements in an Angular application

I'm currently working on an app with the MEAN stack. I've managed to dynamically add form elements, but I'm running into an issue where all dynamically added elements are taking the same data when I use ng-model="something.something". What I ...

Tips on creating a unique d3js tree design

I am a beginner when it comes to d3js and javascript in general. My goal is to create an interactive IP administration overview using d3js by modeling json data. I know that the key tool for this job is likely d3.layout.tree, which will provide me with the ...

Increasing the size of text in CSS with the use of ":hover" and then causing it to return to its original smaller size

Allow me to explain my goal here. I have text displayed on my website that I would like to enlarge when the user hovers over it and then shrink back down when they move their cursor away. The issue I'm facing is that after enlarging the text using t ...

Trouble with setting up custom static route

Greetings! I am currently working on setting up my project in React and here is my current project structure: -public --w ---dist ----bundle.js ---index.html -server --server.js -src --app.js -webpack.config.js -package.json -.babelrc For my server, I am ...

I could really use some assistance with this script I'm working on that involves using ($

Using Ajax for Form Submission: $.ajax({ url: 'process.php', type: 'post', data: 'loginName=' + $("#loginName").val() + 'loginPass=' + $("#loginPass").val(), dataType: 'json', success: func ...

Is it possible to embed an array within an object by utilizing the name attribute in a form?

I am currently developing a full-stack application where I have a form that submits data to one of my post routes. In this form, all input fields are grouped into req.body.model. This is made possible by adding a name attribute with square brackets around ...

What is the best way to include a check mark icon using MUI or Tailwind CSS for every item selected in a dropdown menu?

I need help with adding a small check/tick icon next to the selected value, for example: Operations ✓ when the user chooses operations in the TopicList dropdown list. The TopicList is a class component used to retrieve data from the database which incl ...

Enhancing user experience with jquery autocomplete matching

Currently utilizing the JQuery Autocomplete plugin. It seems that the default behavior is to match from the start, so "foo" matches "fool", but not "bufoon". I am seeking a way for matching to happen anywhere in the text and also in a case-insensitive man ...

Trigger a pop up using AJAX when successful

There is a button that, when clicked, triggers a pop up dialog box with the code below: <div class="button-wrap"><button data-dialog="somedialog" class="trigger">Open Dialog</button></div> The script responsible for activating the ...

How to efficiently filter an array containing nested objects using TypeScript

I'm currently working with a list of menus and submenus: [ { "NUA_ID_Menu": 1, "TXT_Nom_Menu": "Menu 1", "Liste_Sous_Menus": [ { "TXT_Nom_Menu": ...

Utilize the <a> element as a button to submit the data form

I am looking to transfer data from a form to another PHP page without using a button within the form itself. Instead, I have placed a separate button outside of the form for submission. How can I achieve this by sending the form data to the other page? Bel ...

Encountered an issue following deployment to Heroku (Application error)

Introduction I recently created a Login form for my project. The frontend is deployed on Netlify at this link, and the backend is hosted on Heroku which can be accessed here. To view the backend logs, click here Here is a snippet of my index.js file: co ...

Displaying JSON data using Vue.js

fetching JSON data save movieData: {} ...... retrieveMovieData (context, parameter) { axios.get(API.movieData + parameter.id) .then(response => { context.commit('MOVIE_DATA', response.data) }) .catch(error => ...

Using jasmine for mocking jQuery's getJSON callback function is a helpful technique in testing your

In my module, there is a load function that utilizes jQuery's getJSON function to fetch data. load(key,callback){ // validate inputs $.getJSON( this.data[key],'',function(d){ switch(key){ // perform actions on the data bas ...

Is it possible to deactivate an anchor tag based on the result of a conditional statement that returns a string?

I've created an anchor tag (not a button) with text that redirects me to another page <StyledTableCell align="center"> <Link href={`/races/results/${race.id}`}>{race.race_name}</Link> </StyledTableCell> There is a ...

What is the best way to handle a large number of nested AJAX GET requests?

My task involves making numerous AJAX GET requests, which must be nested because each request depends on variables from the response of the previous one. Although I was able to make multiple requests with the example below, it becomes impractical when dea ...

What is the process for encrypting data with javascript and decrypting it with php?

Looking for a way to encrypt data with a JavaScript function to use in a URL passed through an ajax GET request? For example, you could have encrypted data like TDjsavbuydksabjcbhgy which is equivalent to 12345: http://sample.com/mypage/TDjsavbuydksabjcbh ...

Tips for linking my TypeScript document to the server

Recently diving into the world of Angular 2 and seeking to grasp its intricacies. Currently utilizing Visual Studio Code. How can I have the server monitor changes in the TypeScript file? Do I need a compiler to convert it to JavaScript for this purpose? ...