Two Strings

I am currently using my laptop. I prefer using a desktop with a couple monitors; but such is life.

I received a challenge from HackerRank. If you are interested you can check it out here.

In a nutshell you are provided with two strings. The challenge is to return “YES” or “NO” if they do or do not share a common string. A common string is a single character.

Given the requirements one can re state them by saying that you have two sets of characters. Determine if they share a single character.

I will develop a solution using the Eclipse IDE and the Java programming language.

Following are some strings that I used to verify that the code works as required. An edited screen capture follows:

2
hello
world
hi
world
YES
NO

2
be
cat
and
art
NO
YES

4
wouldyoulikefries
abcabcabcabcabcabc
hackerrankcommunity
cdecdecdecde
jackandjill
wentupthehill
writetoyourparents
fghmqzldbc
NO
YES
YES
NO

2
aardvark
apple
beetroot
sandals
YES
NO

The code for the function of interest follows:

    // Complete the twoStrings function below.
    static String twoStrings(String s1, String s2) {

    	// **** create hash map with first string ****
    	HashMap<Character, Integer> hm1 = new HashMap<Character, Integer>();
    	for (int i = 0; i < s1.length(); i++)
    	{
    		char ch = s1.charAt(i);
    		if (!hm1.containsKey(ch)) {
    			hm1.put(ch, 1);
    		}
    	}
    	
    	// **** create hash map with second string ****
       	HashMap<Character, Integer> hm2 = new HashMap<Character, Integer>();
    	for (int i = 0; i < s2.length(); i++)
    	{
    		char ch = s2.charAt(i);
    		if (!hm2.containsKey(ch)) {
    			hm2.put(ch, 1);
    		}
    	}

    	// **** traverse first hash map looking character match in second one ****
    	for (Character ch : hm1.keySet()) {
    		if (hm2.containsKey(ch))
    			return "YES";
    	}

    	// **** ****
    	return "NO";
    }

You can find my complete solution in my GitHub repository.

I will see if I can bump up a notch the complexity and the variety of the challenges.

If you have comments or questions regarding this or any other post in this blog, or if you require assistance developing software at any phase of the life cycle, please leave me a note below.

Keep on learning, experimenting and developing great software.

John

Follow me on Twitter:  @john_canessa

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.