ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Ruby Palindrome Check

Ruby

Goal -- WPM

Ready
Exercise Algorithm Area
1def is_palindrome?(str)
2return true if str.nil? || str.empty?
3
4# Clean the string: remove non-alphanumeric characters and convert to lowercase.
5cleaned_str = str.downcase.gsub(/[^a-z0-9]/, '')
6
7# Compare the cleaned string with its reverse.
8cleaned_str == cleaned_str.reverse
9end
Algorithm description viewbox

Ruby Palindrome Check

Algorithm description:

This Ruby method determines if a given string is a palindrome, meaning it reads the same forwards and backward. It first cleans the input string by removing non-alphanumeric characters and converting it to lowercase, then compares the cleaned string with its reversed version. Palindrome checks are used in natural language processing, coding challenges, and data validation.

Algorithm explanation:

The `is_palindrome?` method checks if a string reads the same forwards and backward. It handles `nil` or empty strings by returning `true`. The core logic involves cleaning the input string: it converts the string to lowercase using `downcase` and removes any characters that are not lowercase letters or digits using `gsub(/[^a-z0-9]/, '')`. This ensures that case and punctuation do not affect the palindrome check. Finally, it compares the `cleaned_str` with its reversed version (`cleaned_str.reverse`). If they are identical, the string is a palindrome, and the method returns `true`; otherwise, it returns `false`. The time complexity is dominated by the `gsub` and `reverse` operations, both of which are O(n), where n is the length of the string. The space complexity is O(n) due to the creation of the `cleaned_str` and its reversed copy.

Pseudocode:

function is_palindrome(input_string):
  if input_string is null or empty:
    return true
  
  initialize cleaned_string by converting input_string to lowercase and removing non-alphanumeric characters
  
  return cleaned_string is equal to reversed cleaned_string