Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Check Palindrome (recursive)

Moderate
0/80
87 upvotes

Problem statement

Determine if a given string ‘S’ is a palindrome using recursion. Return a Boolean value of true if it is a palindrome and false if it is not.

Note: You are not required to print anything, just implement the function. Example:
Input: s = "racecar"
Output: true
Explanation: "racecar" is a palindrome.
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first and only line of the input contains string S.
Output format:
Return a boolean value True or False.
Sample Input 1:
abbba
Sample Output 1:
true
Explanation Of Sample Input 1 :
“abbba” is a palindrome
Sample Input 2:
abcd
Sample Output 2:
false
Explanation Of Sample Input 2 :
“abcd” is not a palindrome.
Constraints:
0 <= |S| <= 10^6
where |S| represents the length of string S.
Hint

Recursively compare characters at the outer ends of the string while moving toward the center.

Approaches (1)
Recursive Approach

To solve this problem, we can use a recursive approach. We'll define a helper function isPalindromeHelper, that takes two pointers, left and right, indicating the current positions in the string to compare.
 

  • Base Case: If the left pointer is greater than or equal to the right pointer, we have checked all the characters in the string, and they match. So, we can return true as the string is a palindrome.
  • Recursive Case: Check if the characters at the left and right pointers are equal:
    • If they are equal, we can recursively call the isPalindromeHelper function by moving the left pointer to the right and the right pointer to the left. This way, we compare the next pair of characters.
    • If unequal, we can immediately return false if the string is not a palindrome.

Algorithm:

  • function isPalindromeHelper(str, left, right):
    • if left >= right:
      • return true
    • if str[left] equals str[right]:
      • return isPalindromeHelper(str, left + 1, right - 1)
    • return false

 

  • function isPalindrome(str):
    • return isPalindromeHelper(str, 0, length(str) - 1)
Time Complexity

O(n), Where n is the size of the input string. 
 

In the worst case, we will perform total (n/2) comparisons.

 

Therefore, the time complexity is O(n).

Space Complexity

O(1)

 

We always return the next recursive call so they won't stack up on the call stack.’
 

Therefore, the space complexity is O(1)

Code Solution
(100% EXP penalty)
Check Palindrome (recursive)
All tags
Sort by
Search icon

Interview problems

Easy Java Solution

static boolean helper(char[] str, int s, int e){

if(s >= e) return true;

if(str[s] != str[e]) return false;

return helper(str, ++s, --e);

}

public static boolean isPalindrome(String str) {

return helper(str.toCharArray(), 0, str.length() - 1);

}

2 views
0 replies
0 upvotes

Interview problems

Check Palindrome(recursive)

public class Solution {

    public static boolean f(String str, int i, int j){

 

        while(i<=j){

            if(str.charAt(i)!=str.charAt(j)){

                return false;

            }

            i++;

            j--;

        }

      return true;

    }

    public static boolean isPalindrome(String str) {

        return f(str,0,str.length()-1);

    }

}

22 views
0 replies
0 upvotes
profile

Interview problems

Check Palindrome (recursive)

compare(String str, int n, int k): This method takes the input string str, the length of the string n, and the current index k. It recursively compares characters from the start (k) and end (n-1-k) of the string until the condition k >= n / 2 is met.

Base case: If k exceeds or equals half the length of the string (k >= n / 2), it returns true, indicating that the string is a palindrome.

Recursive case: If the characters at positions k and n-1-k are equal, it calls the compare method recursively with k incremented by 1. Otherwise, it returns false. time complexity is O(n), where n is the length of the input string. space complexity is O(n), where n is the depth of recursion (or the length of the input string). 

 

Predefined function:

 input string str, reverses it, and compares it with the original string. O(n) time and space

public class Solution {

   static boolean compare(String str, int n, int k){

        if(k>=n/2){

            return true;

        }

        if(str.charAt(k)==str.charAt(n-1-k)){

            return compare(str, n, k+1);

        }

        return false;

    }

    public static boolean isPalindrome(String str) {

  

    int l=str.length();

    return compare(str,l,0);

    }

}

  //     StringBuilder s=new StringBuilder();

    //     s.append(str);


 

    //     StringBuilder ns=new StringBuilder();

    //     ns=new StringBuilder(s).reverse();


 

    //    // ns.append(ns); 

    //     return s.toString().equals(ns.toString());

26 views
0 replies
0 upvotes

Interview problems

Solved by Python

def isPalindrome(string: str) -> bool:
    lstr= list(string)
    cstr= list(reversed(string))
   
    if lstr== cstr:
      return True
    else:
      return False
32 views
0 replies
0 upvotes

Interview problems

Check Palindrome (recursive) -- Java Solution

public class Solution {

    public static boolean isPalindrome(String str) {

        // Write your code here.

        char[] pal = str.toCharArray();

       boolean ans =  helper(0,str.length()-1, pal);

 

       return ans;

    }

    public static boolean helper(int s, int e, char[] pal){

 

       if(s>=e){

           return true;

       }

       if(pal[s]== pal[e])

       return helper(++s,--e,pal);

 

       return false;

    }

}

 

52 views
0 replies
0 upvotes

Interview problems

Data Structures

#C++#Recursion#Palindrome#NotPalindrome

 

Very easiest c++ code for “checking whether the given string be palidrome or not? (Using Recursion)”…

 

we used just given function and not functions are defined to call from isPalindrome function….

 

we just using the given code or function signature …

 

To achieve the solution :no need to define any other functions other than given..

 

My Solution be:

 

int i;

bool isPalindrome(string& s) {

    // Write your code here.

    if(i>=s.size()/2){

        return true;

    }

    if(s[i]!=s[s.size()-i-1]){

        return false;

    }

    i++;

    return isPalindrome(s);

}

 

To solve this problem ,we just used a one global variable named as ‘i' which indicates the current position of string pointer that we checking whether palindrome or not?

 

Time complexity be: O(str.size()/2)~O(str.size())

Space Complexity be:O(str.size())

135 views
0 replies
0 upvotes

Interview problems

solution with detailed explation of each recursion in CPP ☺

#include<string>

 

// her we make it another function for checking the palidrone 

// the base case it i >= n/2 that means the i runs unitil the its grether or equal to n/2

//  so i =0  and n is size of the string  for example if the string is  madam 

// the lenght of string is 5 so the value of n is also 5

// at first recursion the the i is 0 and 5/2 is 2 (0>=2) so the conditon will not satifssatisfied 

// at next point the we check that string element at positon i = 0 is not = to the postion of n-i-1 

// 5 - 0 - 1 = 4 at 4th index since they are equal becuase in  the string madam 

//  0 1 2  3 4     at postion 0 and 4 has same means euqal char 

//  m a d a m     so else will not executed 

 

//   the at next point we agian call fucntion  a recursive call 

//  incrementing the value of i by 1 i+1 and giving the n as its 

 

// at next recursion the value for i is 1 and and n is 5 

// base case check (1>=5/=2) not satisfy 

// check at element 1 and and 5-1-1 means 3 are same or not 

// 0  1  2   3  4   at 1 we have a and at 3rd we have a they are equal 

//  m a  d   a  m   since they are equal then the false not executed 

// recursuve call i is incremented by 1 i=2 and n as its 5

 

// at 3rd  recursion the  value of i is 2 and n is 5

// base condition is (2>=5/2=2) base candition is satisfied her and it return true 

// hense the string is palidrome 

 

bool checkp(int i, int n, string &str)

{

    if(i>=n/2) return true;

 

    if(str[i] != str[n-i-1]) return false;

 

    return checkp( i+1,  n,  str);

 

}

 

bool isPalindrome(string& str) {

    // Write your code here.

    int i =0;

 

    int n = str.size();

 

    return checkp(i, n, str);

 

}
150 views
0 replies
1 upvote

Interview problems

Recursive Soln | O(n/2) | C++

bool checkPalindrome(int i,int j,string &str){

    if(i>=j)return true;

    if(str[i]!=str[j])return false;

    else return checkPalindrome(i+1, j-1, str);

}

bool isPalindrome(string &str) {

     int i = 0;

     int j=str.size()-1;

     return checkPalindrome(i,j,str);

 

      }

 

123 views
0 replies
0 upvotes

Interview problems

cpp solution

bool isPalindrome(string& str) {

    // Write your code here.

    string rev="";

    int len=str.size();

   for(int i=len-1;i>=0;i--){

       rev+=str[i];

   }

    if(rev==str) return true;

    else return false;

}

 

129 views
0 replies
0 upvotes

Interview problems

eaassssssyyyyy cpp code

bool isPalindrome(string& str) {

int n=(str.length()-1);

int flag=0;

int i,j;

for( i=0;i<=n/2;i++ ){

if (str[i] != str[n-i]) {

flag++;

}

}

if(flag==0){

return true;

}

return false;

 

}

114 views
1 reply
0 upvotes
Full screen
Console