Sunday, 23 March 2025

Remove All Occurrences of a Given Character using Two Pointer Approach

 



- ๐—œ๐—ป๐˜๐—ฒ๐—ฟ๐˜ƒ๐—ถ๐—ฒ๐˜„ ๐—ค&๐—” ๐—ฃ๐—ฎ๐—ฐ๐—ธ๐—ฎ๐—ด๐—ฒ ๐—ณ๐—ผ๐—ฟ ๐—ง๐—ฒ๐˜€๐˜ ๐—”๐˜‚๐˜๐—ผ๐—บ๐—ฎ๐˜๐—ถ๐—ผ๐—ป & ๐—ฆ๐——๐—˜๐—ง: https://topmate.io/sidharth_shukla/605319



Problem: Remove All Occurrences of a Given Character

Problem Statement:

Given a string s and a character ch, remove all occurrences of ch from s using the two-pointer approach.

Example 1:

Input: "apple", 'p'
Output: "ale"

Example 2:

Input: "banana", 'a'
Output: "bnn"


Java Solution (Two-Pointer Approach)

public class RemoveCharacter {
public static String removeChar(String s, char ch) { char[] chars = s.toCharArray(); int j = 0; // Pointer for placing valid characters for (int i = 0; i < chars.length; i++) { if (chars[i] != ch) { chars[j] = chars[i]; j++; // Move valid character index forward } } return new String(chars, 0, j); } public static void main(String[] args) { System.out.println(removeChar("apple", 'p')); // Output: "ale" System.out.println(removeChar("banana", 'a')); // Output: "bnn" } }

Explanation (Two-Pointer Approach)

  1. Use Two Pointers:

    • i iterates through the original string.
    • j keeps track of the next position for valid characters.
  2. Skip the Character to Remove:

    • If s[i] is not equal to ch, move it to j position.
  3. Return New String Without the Removed Characters.

Time Complexity: O(n) (single pass through the string)
Space Complexity: O(n) (output string storage)

๐Ÿ”ฅ This is an easy and efficient way to remove a character from a string using two pointers! ๐Ÿš€



*** - ๐—๐—ฎ๐˜ƒ๐—ฎ ๐—œ๐—ป๐˜๐—ฒ๐—ฟ๐˜ƒ๐—ถ๐—ฒ๐˜„ ๐—ค&๐—” ๐—ฃ๐—ฎ๐—ฐ๐—ธ๐—ฎ๐—ด๐—ฒ: https://topmate.io/sidharth_shukla/1170024 - Learn Test Automation with 1:1 Guidance & Interview Preparation: https://lnkd.in/giCxnJJ7. HOLI Discount: Use Code ๐—ฆ๐—œ๐——๐—›๐—”๐—ฅ๐—ง๐—›๐Ÿญ๐Ÿฌ to get 10% Discount (ONLY for first 10 enrollments): https://lnkd.in/giCxnJJ7 ****

No comments:

Post a Comment

All Time Popular Posts

Most Featured Post

Remove All Occurrences of a Given Character using Two Pointer Approach

  - ๐—œ๐—ป๐˜๐—ฒ๐—ฟ๐˜ƒ๐—ถ๐—ฒ๐˜„ ๐—ค&๐—” ๐—ฃ๐—ฎ๐—ฐ๐—ธ๐—ฎ๐—ด๐—ฒ ๐—ณ๐—ผ๐—ฟ ๐—ง๐—ฒ๐˜€๐˜ ๐—”๐˜‚๐˜๐—ผ๐—บ๐—ฎ๐˜๐—ถ๐—ผ๐—ป & ๐—ฆ๐——๐—˜๐—ง: https://topmate.io/sidharth_shukla/6053...