code.ashish.me

Atom feed

Recently added: 02 Count Of Subset Sum, 416 Partition Equal Subset Sum, 01 Subset Sum, 518 Coin Change 2, 983 Minimum Cost For Tickets

344 Reverse String

/**
 * 
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

/* 
 * Write a function that reverses a string. The input string is given as
 * an array of characters char[].
 * 
 * Do not allocate extra space for another array, you must do this by
 * modifying the input array in-place with O(1) extra memory.
 * 
 * You may assume all the characters consist of printable ascii characters.
 * 
 * Example 1:
 * 
 * Input: ["h","e","l","l","o"]
 * Output: ["o","l","l","e","h"]
*/

function reverseString(value) {
  let start = 0
  let end = value.length - 1
  while(start < end){
    let temp = value[start]
    value[start++] = value[end]
    value[end--] = temp;
  }
  return value
}

test('reverse String', () => {
  expect(reverseString(["h","e","l","l","o"])).toEqual(["o","l","l","e","h"])
});

Created 2020-04-10T22:49:16+00:00 · Edit