GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • LeetCodeJavascript.com
  • Star on GitHub

This view

  • Original page
  • New address

GeezerVison is showing leetcodejavascript.com — #2109 - Adding Spaces to a String - LeetCode JavaScript Solutions

Back to all solutions

#2109 - Adding Spaces to a String

Medium • View on LeetCode • View on GitHub
Array String Two Pointers Simulation

Problem Description

You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index.

  • For example, given s = "EnjoyYourCoffee" and spaces = [5, 9], we place spaces before 'Y' and 'C', which are at indices 5 and 9 respectively. Thus, we obtain "Enjoy Your Coffee".

Return the modified string after the spaces have been added.

Solution

/**
 * @param {string} s
 * @param {number[]} spaces
 * @return {string}
 */
var addSpaces = function(s, spaces) {
  let result = '';
  let spaceIndex = 0;

  for (let i = 0; i < s.length; i++) {
    if (spaceIndex < spaces.length && i === spaces[spaceIndex]) {
      result += ' ';
      spaceIndex++;
    }
    result += s[i];
  }

  return result;
};
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.