ℹ️ 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)
2# Handle nil or empty strings as palindromes.
3return true if str.nil? || str.empty?
4
5# Convert to lowercase and remove non-alphanumeric characters for a robust check.
6# This makes 'Racecar' and 'A man, a plan, a canal: Panama' palindromes.
7cleaned_str = str.downcase.gsub(/[^a-z0-9]/, '')
8
9# If the cleaned string is empty or has one character, it's a palindrome.
10return true if cleaned_str.length <= 1
11
12# Compare the cleaned string with its reverse.
13cleaned_str == cleaned_str.reverse
14end
15
16def is_palindrome_iterative(str)
17# A simpler check that is case-sensitive and considers all characters.
18return true if str.nil? || str.length <= 1
19
20left = 0
21right = str.length - 1
22
23while left < right
24if str[left] != str[right]
25return false
26end
27left += 1
28right -= 1
29end
30true
31end
Algorithm description viewbox

Ruby Palindrome Check

Algorithm description:

This Ruby code defines a function to determine if a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same backward as forward. This implementation cleans the string by converting it to lowercase and removing non-alphanumeric characters before performing the check.

Algorithm explanation:

The `is_palindrome?` function checks if a string is a palindrome. It first cleans the input string by converting it to lowercase and removing any characters that are not letters or numbers using `downcase.gsub(/[^a-z0-9]/, '')`. This ensures that variations in casing and punctuation do not prevent a string from being recognized as a palindrome. Then, it compares the cleaned string with its reversed version. If they are identical, the function returns `true`; otherwise, it returns `false`. The time complexity is dominated by the cleaning and reversing operations, which are O(n), where n is the length of the string. The space complexity is also O(n) due to the creation of the cleaned and reversed strings. The `is_palindrome_iterative` helper provides a simpler, case-sensitive check.

Pseudocode:

function is_palindrome(string):
  if string is null or empty:
    return true
  clean string: convert to lowercase, remove non-alphanumeric chars
  if cleaned string length <= 1:
    return true
  reverse the cleaned string
  if cleaned string equals reversed string:
    return true
  else:
    return false