String Reversal

PHOTO EMBED

Tue Sep 14 2021 13:26:49 GMT+0000 (UTC)

Saved by @sangelici94 #javascript #strings #loops #reversal

// SOLUTION 1 - MY SOLUTION (RUNTIME - 104MS, 45.9 MB)
var reverseString = function(s) {
    s.reverse()
};

// SOLUTION 2 (BEST RUNTIME - 80MS)
var reverseString = function(s) {
    // declared here to set a stable loop constant
    // sets the indecies (ie. s.length = 6, indecies -> 0-5)
    let length = s.length - 1;
    
    //a will store value of current str so it isn't lost during reassignment
    let a;
    
    //loop will only need to reach the midpoint to reverse string
    for(let i = Math.floor(length/2); i >= 0; i--){
        a = s[i];
        s[i] = s[Math.abs(i - length)];
        s[Math.abs(i - length)] = a;
    }
    return s;
};

// SOLUTION 3 (RUNTIME - 108MS)
var reverseString = function(s) {
  // set up a for loop with 'i' only iteration up to half the length of 's'
    for(let i = 0; i < s.length / 2; i++) {
        let temp = s[s.length-1-i];
        s[s.length-1-i] = s[i];
        s[i] = temp;
    }    
};
content_copyCOPY

Solutions to reverse a set of strings/items in an array. Solutions include using a for loop (2 examples) and the .reverse() method

https://leetcode.com/submissions/detail/554777828/?from=explore&item_id=879