889274. Remove a Character from a Given Position

Easy

Remove a Character from a Given Position

Summary

The problem is to remove a character from a given position in a string. The goal is to create an algorithm that can efficiently replace or delete a character at a specific index in a sequence of characters.

Detailed Explanation

To solve this problem, we will use the built-in functions provided by programming languages to manipulate strings. We will iterate through the input string until we reach the desired position and then modify the string accordingly.

Here is a step-by-step breakdown of the solution:

  1. Initialize an empty string result that will hold the modified string.
  2. Iterate through the input string from start to the given position minus one.
  3. Add each character to the result string until you reach the desired position.
  4. If the operation is a deletion, set the length of the result string to the current index. This effectively removes the character at the given position and all characters after it.
  5. If the operation is an insertion, append the new character to the result string at the given position.
  6. Return the modified result string.

Here's a diagram illustrating this process:

  Input String: "Hello"
  Desired Position: 3

  Initial Result: ""
  Iterate through input string:
    - Add 'H' to result: "H"
    - Add 'e' to result: "He"
    - ... until we reach position 2
  Modify at desired position (insertion):
    - Append new character '!' to result: "Hel!"

  Final Result: "Hel!"

The time complexity of this solution is O(n), where n is the length of the input string, because we iterate through the entire string once. The space complexity is also O(n) for the same reason.

Optimized Solutions

Java

View on GeeksforGeeks
public static String removeChar(String str, int pos, char newChar) {
    if (pos > str.length()) {
        return str;
    }
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < pos; i++) {
        sb.append(str.charAt(i));
    }
    if (newChar != '\0') {
        sb.append(newChar);
    }
    sb.append(str.substring(pos).replace("\0", ""));
    return sb.toString();
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.