R Program to Check if a String is a Palindrome
Last Updated :
28 Apr, 2025
In this article, we explore a simple yet essential task in programming: checking whether a given string is a palindrome. A palindrome is a sequence of characters that reads the same forwards and backwards, making it a common problem in text processing and string manipulation. We'll delve into the logic and implementation of a program in the R programming language to efficiently determine if a string exhibits this intriguing property, offering practical insights for both beginners and experienced programmers.
Palindrome
Palindrome, well it's a word, phrase, number, or sequence that reads the same forwards and backwards. For instance, "racecar" and "madam" are palindromes, but "hello" and "12345" are not.
Examples:
Input: 'madam'
Output: YES
Input : 'hello'
Output: NO
Concepts related to the topic:
- Case Insensitivity: In many palindrome checks, it's essential to make the comparison case-insensitive to consider uppercase and lowercase characters as equal.
- Whitespace Removal: Removing spaces from the input string is often necessary to check palindromes accurately.
- String Reversal: Palindrome checking involves reversing a string and comparing it to the original.
Native Approach
One of the simplest ways to check for a palindrome in R is by comparing the original string with its reverse.
R
# Function to check if a string is a palindrome
isPalindrome <- function(s) {
s <- tolower(s)
s <- gsub(" ", "", s)
rev_s <- paste(rev(unlist(strsplit(s, ""))), collapse = "")
return(s == rev_s)
}
# Predefined input (change this string as needed)
user_input <- "malayalam"
# user_input<- "mala yalam" # this also give same output as previous because both are plaindrome
# Check if the user input is a palindrome and print YES or NO
if (isPalindrome(user_input)) {
cat("YES\n")
} else {
cat("NO\n")
}
Output:
YES
We convert the string to lowercase and remove spaces for a case-insensitive and space-agnostic comparison. Then, we check if the string is equal to its reverse.
Iterative Method
This method involves comparing characters from the start and end of the string, working towards the center. If all characters match, the string is a palindrome. Here's the code:
R
# Function to check if a string is a palindrome
isPalindrome <- function(s) {
s <- tolower(s)
s <- gsub(" ", "", s)
n <- nchar(s)
for (i in 1:(n %/% 2)) {
if (substr(s, i, i) != substr(s, n - i + 1, n - i + 1)) {
return(FALSE)
}
}
return(TRUE)
}
# Predefined input (change this string as needed)
user_input <- "nitin"
# Check if the user input is a palindrome and print YES or NO
if (isPalindrome(user_input)) {
cat("YES\n")
} else {
cat("NO\n")
}
Output:
YES
- Function isPalindrome:
- The function takes a string s as input.
- It converts the input string to lowercase using tolower to ensure case insensitivity.
- It removes spaces from the string using gsub.
- It calculates the length of the processed string and stores it in n
- The function then begins an iterative loop with n/2 repetitions. Due to the symmetry of the comparison (from both ends towards the centre), this loop only needs to verify the first half of the string.
- If the loop completes without finding any non-matching characters, the function returns YES, indicating that the string is a palindrome.
Using an Extra Variable
This method involves storing characters in an empty variable and comparing it with the original string. We reverse the string by building it character by character in reverse order and then compare it to the original.
R
# Function to check if a string is a palindrome
isPalindrome <- function(s) {
s <- tolower(s)
s <- gsub(" ", "", s)
w <- ""
for (i in s) {
w <- paste(i, w, sep = "")
}
return(s == w)
}
# Predefined input (change this string as needed)
user_input <- "madam"
# Check if the user input is a palindrome and print YES or NO
if (isPalindrome(user_input)) {
cat("YES\n")
} else {
cat("NO\n")
}
Output:
YES
- The isPalindrome function:
- Converts the input string s to lowercase using tolower to make the comparison case-insensitive.
- Removes spaces from the string using gsub.
- Initializes an empty string w.
- Iterates through each character in the modified string, reversing the characters and storing them in w.
- The code then compares the original modified string s with the reversed string w to determine if they are equal.
- If they are equal we get our output as YES.
Using Inbuilt Functions
R provides convenient inbuilt functions to reverse strings. We use rev() and strsplit() to reverse the string and then compare it with the original.
R
# Function to check if a string is a palindrome
isPalindrome <- function(s) {
s <- tolower(s)
s <- gsub(" ", "", s)
rev_s <- paste(rev(strsplit(s, NULL)[[1]]), collapse = "")
return(s == rev_s)
}
# Predefined input (change this string as needed)
user_input <- "13431"
# Check if the user input is a palindrome and print YES or NO
if (isPalindrome(user_input)) {
cat("YES\n")
} else {
cat("NO\n")
}
Output:
YES
- The isPalindrome function starts by converting the input string s to lowercase using tolower(s) to ensure a case-insensitive comparison.
- It then uses gsub(" ", "", s) to remove spaces from the string, making it space-agnostic.
- Next, the code reverses the processed string s using rev and paste, storing the result in rev_s.
- Finally, it checks if the original string s is equal to the reversed string rev_s and returns YES if they match, indicating a palindrome, or NO otherwise.
Similar Reads
How to check whether a passed string is palindrome or not in JavaScript? We are given a string, our task is to find string is palindrome or not. A palindrome is a series of numbers, strings, or letters that, when read from right to left and left to right, match each other exactly or produce the same series of characters. in simple words when number strings or characters
4 min read
Palindrome String Given a string s, the task is to check if it is palindrome or not.Example:Input: s = "abba"Output: 1Explanation: s is a palindromeInput: s = "abc" Output: 0Explanation: s is not a palindromeUsing Two-Pointers - O(n) time and O(1) spaceThe idea is to keep two pointers, one at the beginning (left) and
13 min read
Return a Palindromic String after removing minimum length Prefix from given String Given a string B, the task is to find the minimum length prefix of the string which, when removed and added to the end of the string, will make the string a palindrome. Return the palindromic string. If no such string exists, we need to determine that. Examples: Input: "aabb"Output: "abba"Explanatio
5 min read
Longest Palindromic Substring using hashing in O(nlogn) Given a string S, The task is to find the longest substring which is a palindrome using hashing in O(N log N) time. Input: S: âforgeeksskeegforâ, Output: âgeeksskeegâ Input: S: âGeeksâ, Output: âeeâ Hashing to Solve the Problem:The hashing approach to solving the longest palindromic substring proble
11 min read
Find Longest Palindromic Subsequence II Given a string s, return the length of the longest good palindromic subsequence in s such that:It has an even length.No two consecutive characters are equal, except the two middle ones.Example:Input: s = "bbabab"Output: 4Explanation: The longest good palindromic subsequence of s is "baab".Input: s =
8 min read
JavaScript Program to Check if a Given String is a Rotation of a Palindrome In this article, we will see how to check a given string is a rotation of a palindrome. A palindrome is a string that remains the same when its characters are reversed (e.g., "racecar" is a palindrome).Example:Input: str = "racecar"Output: true // "racecar" is a rotation of a palindrome "racecar"Inp
6 min read
Python Program To Check String Is Palindrome Using Stack A palindrome is a sequence of characters that reads the same backward as forward. Checking whether a given string is a palindrome is a common programming task. In this article, we will explore how to implement a Python program to check if a string is a palindrome using a stack. Example Input: str =
3 min read
JavaScript Program to Check if an Array is Palindrome or Not A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. To check if an array is a palindrome, compare it to its reverse version. If they match, it's a palindrome. Given an array, the task is to determine whether an array is a palindrome. Exam
3 min read
How to Check if Characters are Present in a String in R. In this article, we will learn how to check the presence of a character, substring or number in a string using R Programming Language. This can be useful for tasks where we want to filter data, pattern matching or data cleaning. We generally use grepl() function, a versatile tool that is used for ch
6 min read
Palindrome Number Program in C Palindrome numbers are those numbers that remain the same even after reversing the order of their digits. In this article, we will learn how to check whether the given number is a palindrome number using C program.ExamplesInput: 121Output: YesExplanation: The number 121 remains the same when its dig
3 min read