Evan bio photo

Evan

Noticing Birds.

Email LinkedIn Public Key Github

Many interview questions about string manipulation are checking for the candidate’s skills on writing loops. Often times, the problem can be solved with more advanced regular expressions.

Here is an example question:

Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2bc5a3. If the “compressed” string would not become smaller than the original string, your method should return the original string.

You can solve this one with matching groups, and backreferences.

string.gsub(/(.)\1+/i) { |m| "#{m[0]}#{m.length}" } – Demo

Breaking it down, string.gsub! finds a pattern throughout on the string variable, and replaces it with the block passed as the second option. The ! changes the string in place.

/(.)\1+/i is a regular expression that matches repeated characters. (.) creates a matching group around any one character. The \1 represents the character that was captured in the matching group. Having the i at the end ensures case insensitivity.

By passing the block { |m| "#{m[0]}#{m.length}" } to gsub!, we can have more control over how matches are replaced. This block goes over each matched group of repeated characters and replaces the repeated characters a single matched character and the length of the captured group.

While this regex based solution solves the given problem, it’s not what the interviewer is looking for, so it’s a correct failing answer.

Never the less, here is a little sample of it working.

require 'minitest/autorun'

def functo(str)
  new_str = str.gsub(/(.)\1+/i) { |m| "#{m[0]}#{m.length}" }
  return str if new_str.length == str
  print str
  new_str
end

class MyprojectTest < Minitest::Test
  def test_handles_given_example
    assert_equal functo('aabcccccaaa'), 'a2bc5a3'
  end 
  def test_super_smol
    assert_equal functo('abc'), 'abc'
  end
  def test_smol
    assert_equal functo('abcc'), 'abc2'
  end
end