~/coding-interview/replace-all-spaces-string-with.md

Replace all spaces in a string with %20

// TL;DR

Count spaces first to find the new length, then iterate backwards replacing spaces with %20. Working backwards avoids overwriting characters you haven't processed yet.

Replace all spaces in a string with %20

Problem Statement

Replace all spaces in a string with ‘%20’ (three characters). Do this in place and assume you have enough space in array

Solution (Simple)

This is the simplest solution which many people might think.

  • Iterate from left side (begining)
  • After encountering a space, first shift entire array by 2 places.
  • Put %20 at consecutive location
  • Repeat this process

Obviously, if you see you need to shift the remaining array as many times as number of spaces. And, is not an efficient algorithm.

I will not put this silly code.

Complexity

The complexity would be close to O(n^2)

A Better Solution

If you start from left side, you saw we need to shift the array. What if we start from the right side.

  • First calculate number of spaces in array, this will help in calculating the resultant last index
  • Start iterating from right most side.
  • Maintain two index counters. One for original array characters, other for resultant index positions.
  • Start copying character one by one.
  • If found space, just copy consecutive %20

At the end, you will achieve the purpose. Lets see the code

private static int countSpaces(char[] input) {
   int c = 0;
   for (int i=0; i<input.length; i++) {
      if (input[i] == ' ') {
         c ++;
      }
   }
   return c;
}

public static int replace(char[] input, int len) {
   int spaces = countSpaces(input);
   if (spaces == 0) return len;
   
   int lastIndex = (len-1) + (2 * spaces);
   int resultIndex = lastIndex;
   
   for (int i=len-1; i>=0; i--) {
      if (input[i] == ' ') {
         //copy %20
         input[lastIndex] = '0';
         input[lastIndex-1] = '2';
         input[lastIndex-2] = '%';
         lastIndex -= 3;
      }
      else {
         //copy actual characters
         input[lastIndex] = input[i];
         lastIndex --;
      }
   }
   
   return resultIndex;
}

Complexity

The complexity is O(n)

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Valid Palindrome - Leet Code Solution

Valid Palindrome - Leet Code Solution

Problem Statement Given a string, determine if it is a palindrome, considering…

Valid Anagrams - Leet Code Solution

Valid Anagrams - Leet Code Solution

Problem Statement Given two strings s and t , write a function to determine if t…

First Unique Character in a String - Leet Code Solution

First Unique Character in a String - Leet Code Solution

Problem Statement Given a string, find the first non-repeating character in it…

Reverse String - Leet Code Solution

Reverse String - Leet Code Solution

Problem Statement Write a function that reverses a string. The input string is…

Rotate Image - Leet Code Solution

Rotate Image - Leet Code Solution

Problem Statement You are given an n x n 2D matrix representing an image, rotate…

Validate Sudoku - Leet Code Solution

Validate Sudoku - Leet Code Solution

Problem Statement Determine if a 9x9 Sudoku board is valid. Only the filled…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…