Thursday, February 18, 2021

HackerRank - Two Strings

Our next challenge from HackerRank is to see if two strings contain a common substring, it goes on to say that substring could even just be one letter. Again, this one is rated as easy and I hope it lives up to that.

The initial boilerplate to plug things into:

static string twoStrings(string s1, string s2) {


And a test case:


Result YES

And one more for good measure:


Result NO

My first attempt at it involves breaking one of the strings into a char array so that I can use IndexOfAny which only takes in a char array. Converting string to char array is very easy since there is a ToCharArray method on string. Lets see how this looks and run it against their tests:

static string twoStrings(string s1, string s2)
    var charsOfFirstWord = s1.ToCharArray();
    var index = s2.IndexOfAny(charsOfFirstWord);
    var success = index > -1;
    return success ? "YES" : "NO";

Initial tests pass and then running it against the full suite, they also pass! Huzzah! This one really was easy. Whew, nice change from that last one.

We could tidy this up a bit more to reduce the number of lines. In fact we could one line this (though I question readability) into:

static string twoStrings(string s1, string s2)
    return s2.IndexOfAny(s1.ToCharArray()) > -1 ? "YES" : "NO";

You can find this test at HackerRank - Two Strings

1 comment:

  1. Fun88 Casino Review and Bonuses
    Check out our 퍼스트 카지노 fun88 Casino review for the complete info fun88 soikeotot and bonuses. Read how to claim the welcome bonus ラッキーニッキー and find out more! Play now! Rating: 4.9 · ‎Review by Vienne Garcia


HackerRank - SherlockAndAnagrams

Sherlock and Anagrams, oh what a title. Let’s see what HackerRank has in store for us next. This one is rated as medium and the blurb for it...