DDSA Solutions

Remaining String

Time: O(n)
Space: O(n)
Advertisement

Intuition

Given string, remove all occurrences of a character and return remaining string after kth removal.

Algorithm

  1. 1Count positions of target character. If fewer than k occurrences: return original. Remove first k occurrences.

Common Pitfalls

  • Build result by skipping the kth occurrence (1-indexed). Simple O(n) scan.
Remaining String.java
Java
// Approach: Count occurrences of character c. Find the position after the k-th occurrence and return suffix.
// Time: O(n) Space: O(n)
class Solution {
    public String printString(String s, char ch, int count) {
        StringBuilder result = new StringBuilder();
        int flag = 0;

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == ch && flag == 0) {
                count--;
                if (count <= 0)
                    flag = 1;
            } else if (flag == 1)
                result.append(c);
        }

        return result.toString();
    }
}
Advertisement
Was this solution helpful?