How to find the first repeated character in a string with Ruby

1 Answer

0 votes
require 'set'

# Finds the first character that repeats as you scan a string from left to right.
# 
# @param str [String] The input string to evaluate.
# @return [String, nil] The first repeated character, or nil if no characters repeat.
def find_first_repeated_character(str)
  seen = Set.new
  
  # Iterate through each character and find the first one where add? returns nil (already exists)
  str.each_char.find { |char| !seen.add?(char) }
end

# --- Test Cases ---
test_cases = [
  "abca",
  "abcbd",
  "abcde",
  "abcdxypcbop"
]

test_cases.each do |text|
  result = find_first_repeated_character(text)
  display_result = result || "None"
  puts "Input: \"#{text}\" -> First Repeated: #{display_result}"
end


# run:
#
# Input: "abca" -> First Repeated: a
# Input: "abcbd" -> First Repeated: b
# Input: "abcde" -> First Repeated: None
# Input: "abcdxypcbop" -> First Repeated: c
#

 



answered 6 days ago by avibootz
...