code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

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