Posted in Career, Interview
4/04 2011

Interview Questions Part 1: Reverse a String

As indicated in the last post, I’ve been on an extensive job hunt. I thought it would be useful to help those of you that may be going on interviews to know what kinds of questions I fielded. I’m going to try to give you the most frequently asked in order, but I’m horrible with taking notes during interviews.

First up is the classic reverse a string problem. I think I got asked this at least 6 times during interviews. It’s like a warm-up to coding question, but you’d be amazed at how many people fumble on this exercise.

The first method I’m going to use is the easiest to remember/implement:

public static string Reverse( string text )
{
    char[] charArray = text.ToCharArray();
    Array.Reverse( charArray );
    return new string( charArray );
}

The method takes a string as a parameter, copies the string to a char array using the ToCharArray() instance method, reverses the characters in the array using the Reverse() instance method, then returns the reversed char array. Pretty simple right?

 

There are always more than one way to solve a problem so I’m going to show you some other implementations of methods that reverse strings.

Reading from end of string

public string Reverse(string text)
{
    string reverse;
    for (int i = text.Length - 1; i > -1; i--)
    {
        reverse += text[i];
    }
    return reverse;
}

Reverse using stack (Push and Pop)

public static string StackReverse(string text)
{
    Stack<char> revStack = new Stack<char>();
    foreach (char c in input)
    {
        revStack.Push(c);
    }

    StringBuilder sb = new StringBuilder();
    while (revStack.Count > 0)
    {
        sb.Append(revStack.Pop());
    }

    return sb.ToString();
}

Hopefully, now when you encounter this problem in an interview you won’t have any issues solving this problem with confidence. Until next time…

 

-DPB

 

USER COMMENTS

Track comments via RSS 2.0 feed. Feel free to post the comment, or trackback from your web site.

Currently there are no comments related to article "Interview Questions Part 1: Reverse a String".