Reverse elements of a string array

15,818

Solution 1

Here you go, no support variables, no .net functions :) But it makes the assumptions that all the strings in the array have length 1 ( as they do in the code you posted).

string[] myString = {"a","b","c","d", "e"};
for(int i = 0; i < myString.Length/2; i++)
{
   myString[i] += myString[myString.Length -1 -i];
   myString[myString.Length -1 -i] = ""+myString[i][0];
   myString[i] = "" + myString[i][1];
}

Solution 2

Since you cannot use a temporary variable, the best I can think of is appending the strings first and then removing the appended part again:

// append last strings to first strings
for(int i = 0; i < myString.Length / 2; i++)
{
    myString[i] = myString[i] + myString[myString.Length - i - 1];
}

// copy first half to last half
for(int i = myString.Length / 2 + 1; i < myString.Length; i++)
{
    myString[i] = myString[myString.Length - i - 1]
                      .SubString(0, 
                              myString[myString.Length - i - 1].Length 
                               - myString[i].Length);
}

// remove useless part from first half
for(int i = 0; i < myString.Length / 2; i++)
{
    myString[i] = myString[i].SubString(
                                  myString[myString.Length - i - 1].Length 
                                   - myString[i].Length);
}

Stupid approach? Yes. But no additional variables are involved.

Solution 3

string[] myString = {"a","b","c","d"}

for(int = (myString.Length - 1); int >= 0; i--) {
    string rev =  myString[i];
    Console.Write(rev);
}

Solution 4

The right answer in your interview is "Why would you NOT use the class libraries?" But then say, "Well if I needed to write a customized method because the libraries don't support the need...". Then I would show both methods and argue when to use each method. If they had a problem with this explanation then I wouldn't want to work there anyway.

With Libraries:

string[] myString = {"a","b","c","d"};
List<string> list = myString.ToList();
list.Reverse();
myString = list.ToArray();

Without:

string[] myString = {"a","b","c","d"};
string[] newString = new string[myString.Length];
for (int i = 0, j = myString.Length - 1; i < myString.Length && j >= 0; i++, j--)
{
    newString[j] = myString[i];
}
myString = newString;

Solution 5

Sorry I posted a wrong answer... here's the verified one:

     int k = len - 1;
    for(int i = 0; i<len/2; i++)
    {
        myString[i] = myString[i]+"."+myString[k--];
    }
    for(int i = len/2; i<len; i++)
    {
        myString[i] = myString[k].substring(0, 1);
        myString[k] = myString[k--].substring(2,3);
    }

However, just consider this a pseudo-code... I did not check for .NET syntax.

Share:
15,818
lbrahim
Author by

lbrahim

Engineer in disguise....

Updated on June 04, 2022

Comments

  • lbrahim
    lbrahim almost 2 years

    string[] myString = {"a","b","c","d"}
    //Reverse string algorithm here
    myString = {"d","c","b","a"}
    I have been asked to do so in an interview without the help of any temporary variable or .NET class, string methods, etc to reverse the elements of the same string array. I was told to use basic programming constructs like loops. Since, I am up for another interview today, I am in a hurry to know whether this is actually possible because I could not find a solution to this.

    • Magnus Grindal Bakken
      Magnus Grindal Bakken over 10 years
      We're not here to do your job interview for you. At least show some things you've tried.
    • Nisarg Shah
      Nisarg Shah over 10 years
      You were asked to store the values in reverse or update the array?
    • S_F
      S_F over 10 years
      I'm pretty sure there would be no downvotes if OP never metioned the job interview...
    • Nisarg Shah
      Nisarg Shah over 10 years
      @MagnusGrindalBakken We will not be solving this for his interview. It will be for our knowledge or if we have then we can share with him
    • Magnus Grindal Bakken
      Magnus Grindal Bakken over 10 years
      @NisargShah Note the second part of my comment. There's nothing wrong with asking for help about school problems, job interviews, or work projects, but you have to show that you've made an attempt.
    • xanatos
      xanatos over 10 years
      For ints (and similar types) you can use the xor trick, but for other types you'll need a temporary variable... Or use the stack as a temporary variable. You could cheat by using a parameter of a function as as temporary variable, but a parameter is still a variable.
    • Nisarg Shah
      Nisarg Shah over 10 years
      Can you resize array size in basic programming?
    • Nisarg Shah
      Nisarg Shah over 10 years
      If by any case you can resize array then first double the size of array. Later add values in reverse order and overwrite the first half of array with reversed values. Now resize the array with half size. Thats all...
    • lbrahim
      lbrahim over 10 years
      @MagnusGrindalBakken I did this Needless to say it did not work so, I did not post it here.Technically, you would just be answering my previous encounter of the problem. There is no guarantee it will ever be asked later.
    • Bernhard Barker
      Bernhard Barker over 10 years
      @S_F In that case everyone might assume it's homework and it would get downvoted a whole lot more. StackOverflow guidelines dictates that you should show a sufficient attempt at solving the problem oneself before asking here, the lack of this is likely the only reason it was downvoted.
  • Microsoft DN
    Microsoft DN over 10 years
    He wants to do it without using any existing methods
  • Nisarg Shah
    Nisarg Shah over 10 years
    OUt of question. It is from .net
  • Hemario
    Hemario over 10 years
    ah, without .NET classes. Ah well, I'll leave the answer for future reference.
  • Nisarg Shah
    Nisarg Shah over 10 years
    this is linq and also .net way of doing it
  • Heslacher
    Heslacher over 10 years
    As stated: without the help of any temporary variable or .NET class, string methods.. -> SubString usage ;-(
  • Vincent van der Weele
    Vincent van der Weele over 10 years
    @Heslacher that's no .NET, that's the SubString that I implicitly implemented myself but just did not show ;)
  • xanatos
    xanatos over 10 years
    @Heuster I don't think SubString is implementable without temporary variables :-)
  • Vincent van der Weele
    Vincent van der Weele over 10 years
    @xanatos I'm afraid so too. But neither is string concatenation since strings are immutable. The question would make more sense to me for an array of integers (so the XOR trick could be used).
  • Jean Logeart
    Jean Logeart over 10 years
    You use tmp variable in your solution. You just hide it making the code ugly and less efficient...
  • Bernhard Barker
    Bernhard Barker over 10 years
    That seems like a ridiculous assumption. If they're all length 1, the logical thing to do would be to have a char[] instead.
  • Save
    Save over 10 years
    @Dukeling If we were in the logic domain, you wouldn't be asked not to use .net funcions or accessory variables. I tried to solve the ask just as he presented it.
  • Bernhard Barker
    Bernhard Barker over 10 years
    The example is just that, an example. The description doesn't mention that we're limited to length 1 strings and it seems like a very strange constraint to put on strings, so my logical assumption is that the example only uses length 1 strings because that's less typing than longer strings. Yes, I'd be a lot happier with a wild-card-based approach.
  • Bernhard Barker
    Bernhard Barker over 10 years
    Is there a specific reason you didn't just put all 3 statements in a single loop?
  • Vincent van der Weele
    Vincent van der Weele over 10 years
    @Dukeling stupidity :) I wondered the same after typing, but then I thought: maybe it's more clear this way (probably not)
  • lbrahim
    lbrahim over 10 years
    Thanks @Save I was asked and therefore, asked for elements of length 1 in a string array. So it works and answers my question.
  • DanielV
    DanielV about 9 years
    cannot convert from 'System.Collections.Generic.List<string>' to 'System.Array'
  • DanielV
    DanielV about 9 years
    It will not work and throw: cannot convert from 'System.Collections.Generic.List<string>' to 'System.Array'
  • Athena
    Athena almost 7 years
    Please provide answers that do not require clarification from the asker.
  • user1438038
    user1438038 almost 7 years
    While your post might answer the question, please also provide a short explanation what your code actually does and how it solves the initial problem. Don't just drop a couple of poorly formatted lines of code.
  • Koosh
    Koosh about 6 years
    I agree with you here. I don't know why everyones makin it so difficult
  • ProgrammingLlama
    ProgrammingLlama almost 6 years
    There's a reason for that. The question states that you can't use a temporary variable, which I'd argue yours does.
  • Eric Lippert
    Eric Lippert almost 6 years
    The reason to say "without using libraries" is because someone had to write that library. If you are interviewing for a job that involves writing libraries, assuming that the library is already written is a non-starter.
  • Benj Sanders
    Benj Sanders almost 6 years
    @EricLippert correct, no contest. But, the specific assignment involved not using libraries available that are highly optimized. Unless you are removing dependencies, using the library is the correct method, otherwise why ever use a library, right?