-2

I tried a challenge on edabit.com It is about "strangepairs". So the task is to return true if "The 1st string's first letter = 2nd string's last letter. The 1st string's last letter = 2nd string's first letter." ...also return true if both strings are null.

Who can spot the difference? Thanks in advance.

My Attempt:

public class Program
{
    public static bool IsStrangePair(string str1, string str2)
    {

            if (str1[0] == str2[str2.Length - 1] && str2[0] == str1[str1.Length - 1])
                return true;

            if (str1 == "" && str1 == str2)
                return true;

            return false;
        }
}

Their answer:

using System.Linq;

public class Program
{
    public static bool IsStrangePair(string str1, string str2)
    {
            if(string.IsNullOrEmpty(str1) || string.IsNullOrEmpty(str2))
            {
                return str1 == str2;
            }

            return str1.First() == str2.Last()
                && str2.First() == str1.Last();
    }
}

I can't spot the difference. Can someone please tell me why my solution produces an IndexOutOfRangeException and theirs doesn't? My solution works overall, all but for 2 cases. Sadly I can't see what the cases are, and I don't understand under which circumstances would produce this error.

1
  • 1
    You are not accommodating for null strings. You also need to put your null and empty checks at the beginning. Afterwards, if the strings are not null or empty you can try and access the first and last characters. Right now, if the string is empty you are still trying to access characters that are not there hence the index out of range error.
    – Ivan Kahl
    Feb 10, 2020 at 19:11

1 Answer 1

4

the task is to ... return true if both strings are null.

Your code crashes if both strings are null.

You should always try the test cases that are specifically mentioned in the assignment.

You should internalize this for interviews as well; I frequently have interview candidates where I give them a coding task, I give them some sample inputs and outputs, and they never bother to verify that their code works on the sample inputs and outputs.

I don't understand under which circumstances would produce this error.

Always think about what test cases would crash your code. Think like an attacker. Suppose you were given your code and given the task "find a way to make it crash". What would you do? The easiest thing to start with is null and empty strings, so start with those.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.