Array ( [0] => [1] => questions [2] => Strings [3] => Palindrome- )
Given a String. You have to find the given string is palindrome or not (Palindrome means it should be same when the string is reversed). Note: Work with numbers also from your end.
First line contains a string.
Print Yes if the given string is palindrome else No.
abba
Yes
abcdcba
Yes
abbbbaa
No
Login to see Discussion
Approach 1: Traverse the entire string
Step-i) take two variables
Step-ii) initialize first variable to 0 and other variable to string length -1
Step-iii) compare characters at both the index positions
Step-iv) if they are not equal return "No"
Step-v) increment first variable and decrement the second variable
Step-vi) repeat steps iii,iv and v until first variable reaches lenght of string and second variable reaches 0
Step-vii) if all characters are equal return "Yes"
Time Complexity: O(n)
Space Complexity: O(1)
Approach 2: Traverse only upto half of string
Step-i) take two variables
Step-ii) initialize first variable to 0 and other variable to string length -1
Step-iii) compare characters at both the index positions
Step-iv) if they are not equal return "No"
Step-v) increment first variable and decrement the second variable
Step-vi) repeat steps iii,iv and v until first variable is less than second variable
Step-vii) if all characters are equal return "Yes"
Time Complexity: O(n/2)
Space Complexity: O(1)
Approach 3: copy to other string
Step-i) copy the given string to other string
Step-ii) reverse the copied string
Step-iii) now check whether both strings are equal or not
Step-iv) if they are equal return "Yes" else return "No"
Time Complexity: O(n)
Space Complexity: O(n)
Note :
Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.
Login to see Solution