Press "Enter" to skip to content

CodeSignal Arcade – commonCharacterCount

I want to excel in my Python coding skills and for that I went to a website called CodeSignal and started participating in the arcade mode which gives you a loooong list of coding tests, today I’ll write about test #10 “commonCharacterCount”

Objective

Given two strings, find the number of common characters between them.

Example

For s1 = "aabcc" and s2 = "adcaa", the output should be commonCharacterCount(s1, s2) = 3.

Strings have 3 common characters – 2 “a”s and 1 “c”.

Input/Output

  • [execution time limit] 4 seconds (py3)

  • [input] string s1

    A string consisting of lowercase English letters.

    Guaranteed constraints:
    1 ≤ s1.length < 15.

  • [input] string s2

    A string consisting of lowercase English letters.

    Guaranteed constraints:
    1 ≤ s2.length < 15.

Walkthrough

My idea for this was very simple – change the provided strings to lists, and then go through them and count the common characters, let’s look at an example:

  • We get two strings
    • s1 = "aabcc"
    • s2 = "adcaa"
  • Next we convert them to lists
    • s1_list = ['a', 'a', 'b', 'c', 'c']
    • s2_list = ['a', 'd', 'c', 'a', 'a']
  • And create a counter common=0
  • Then we iterate through the the first list s1_list
    • check if the character ‘a’ exists in the s2_list
    • if so, we add + 1 to the counter,
    • and delete the common character from the s2_list
  • At the end we return the counter variable common

This is how it looks written in Python3:

def commonCharacterCount(s1, s2):
    s1_list=list(s1)
    s2_list=list(s2)
    common=0
    for i in s1_list:
        for s in s2_list:
            if i==s:
                common+=1
                s2_list.remove(s)
                break
    return common

Now that I had the opportunity to compare my solution to the ones submitted by other users I can say that mine was the “dummy version” – but hey, it works, doesn’t it?

commonCharacterCount test result

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.