skip to Main Content

In JavaScript I have a simple function I used to reverse a string, but my trainer at work says that I can cut the processing time in half within my for loop. My trainer doesn’t want me to use the split/reverse/join functions. So that is why I am doing this in a for loop.

At first I thought using the charAT() function was the best way to achieve this, then I switched to just using brackets + the index position.

Currently scratching my head on how to make this more optimal and am wondering if it is maybe not a problem of the contents of the for loop, but maybe how I structured it in the first place?

function reversalFunct(initString) {

   let reverseString = '';

    for (let i = initString.length - 1; i >= 0; i--){
        reverseString += initString[i];
       
    }
    

    return reverseString;
  
}

2

Answers


  1. Even within the training context, an array based collector for aggregating the reversed string data does not contradict the algorithm, the trainer/teacher might have in mind.

    Thus, create a result array of same length of string and initialize a counter value of rounded half the length of the string’s length. Count down this value to zero while separately incrementing a left side index starting from -1 and decrementing a right side index starting from the string’s length.

    Then assign the string’s right index related character to the array’s left index position and the string’s left index related character to the arrays right index position. The iteration steps have been cut to half and the result array gets returned as its own joined string value representation.

    function reverseString(value) {
      value = String(value);
    
      let idxLeft = -1;
      let idxRight = value.length;
    
      let count = Math.ceil(idxRight / 2);
      let result = new Array(idxRight);
    
      while (count--) {
        result[++idxLeft] = value[--idxRight];
        result[idxRight] = value[idxLeft];
      }
      return result.join('');
    }
    
    console.log(
      'Hello World =>', reverseString('Hello World')
    );
    console.log(
      'Anna Otto =>', reverseString('Anna Otto')
    );
    
    console.log(
      'null =>', reverseString(null)
    );
    console.log(
      'undefined =>', reverseString()
    );
    .as-console-wrapper { min-height: 100%!important; top: 0; }
    Login or Signup to reply.
  2. You can think of the inversion problem as mirroring the string.

    The first letter of the input string should end up at the last position in the result. In the same way, the last letter of the input string should end up at the first position in the result.

    Therefore, you can iterate your input string only until half of its length and build the result from the middle part adding to the left and to the right of that center as you go.

    You will have to take into account that if the length of the string is odd you have to start the result string with the letter in the middle:

    const text = 'hello world';
    
    function invertString(str = '') {
        const idx = Math.floor(str.length / 2);
        let result = str.length % 2 === 0 ? '' : str[idx];
    
        for (let i = idx - 1; i >= 0; i--) {
            const prevIndex = i;
            const nextIndex = str.length - i - 1;
    
            result = str[nextIndex] + result + str[prevIndex];
        }
    
        return result;
    }
    
    const inverted = invertString(text);
    console.log(inverted);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search