Num Repeats

Write a method that takes in a string and returns the number of letters that appear more than once in the string. You may assume the string contains only lowercase letters. Count the number of letters that repeat, not the number of times they repeat in the string.

Thought Process: 

# 0 1 2 3 4
# c a d a c

  • Check each letter in string against the rest of the array
  • If it appears more than once, count += 1
  • Store repeated letters in a hash
  • Count how many letters are in hash and return that value

c == a? string[0] == string[1]
c == d? string[0] == string[2]
c == a? string[0] == string[3]
c == c? string[0] == string[4]
a == d? string[1] == string[2]
a == a? string[1] == string[3]
a == c? string[1] == string[4]
d == a? string[2] == string[3]
d == c? string[2] == string[4]
a == c? string[3] == string[4]

Provided Solution:

Screen Shot 2016-08-24 at 11.16.36 AM

My solution:

Example: “aaa” => 1

1. Create a hash called ‘count’ to store each unique letter and its count.
2. Compare each letter against the rest of the letters in the string by incrementing
idx1 and idx2.

string[0] == string[1]    a == a?
string[0] == string[2]   a == a?
string[1] == string[2]    a == a?

3. If it repeats, count +=1 and store it in the hash.
count[string[0]] += 1 => count = {‘a’ => 3}

4. Count the number of key-value pairs in the count hash by using count.length and return that value.

screen-shot-2016-09-22-at-11-58-45-pm

IMPORTANT: 

This is how you store key-value pair in a hash:   HASH_NAME[KEY] += VALUE

Advertisements
Num Repeats

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s