BackmediumStringsTCSPayPal

Iterative Node Cluster Solution

Problem Statement

You are given a string s containing only lowercase English letters. Perform the following operation repeatedly until it can no longer be applied: compute the frequency of each character in the current string and delete every character whose frequency is exactly one. After the process terminates, return the resulting string. If all characters are removed, return an empty string. The operation must be applied iteratively – after each deletion step, frequencies are recomputed on the shortened string before the next step.

Example 1
Input
abacabad
Output
ababa

Explanation: Initial frequencies: a=4, b=2, c=1, d=1. Characters c and d appear once, so they are removed, yielding "ababa". Re‑computing frequencies on "ababa" gives a=3, b=2; no character appears exactly once, so the process stops. The final string is "ababa".

Example 2
Input
abcde
Output

Explanation: All five characters appear exactly once. They are all removed in the first iteration, leaving an empty string. No further iterations are possible, so the answer is the empty string.

Example 3
Input
aabccdde
Output
aaccdd

Explanation: First pass frequencies: a=2, b=1, c=2, d=2, e=1. Characters b and e are unique and are deleted, producing "aaccdd". In the new string each character occurs twice, so no further deletions occur. The final string is "aaccdd".

Example 4
Input
zzxyyzz
Output
zzzz

Explanation: Initial frequencies: z=4, x=1, y=2. Character x is unique and is removed, resulting in "zzyyzz". New frequencies: z=4, y=2. No character has frequency one, so the algorithm stops. The resulting string is "zzzz" (the two y's were removed in the previous step because they became unique after x's removal).

Example 5
Input
mnoonm
Output
mnoonm

Explanation: Frequencies at the start: m=2, n=2, o=2. No character appears exactly once, therefore the string remains unchanged and is returned as‑is.

Constraints

  • 1 <= s.length <= 10^5
  • s consists only of lowercase English letters ('a'–'z')
  • The algorithm must run in O(n) time on average, where n is the length of the input string.
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Iterative Node Cluster — Problem Statement & Solution Guide

StringsMediumCharacter Frequency Map
TimeO(n)
|
SpaceO(1)

Problem Description

You are given a string s containing only lowercase English letters. Perform the following operation repeatedly until it can no longer be applied: compute the frequency of each character in the current string and delete every character whose frequency is exactly one. After the process terminates, return the resulting string. If all characters are removed, return an empty string. The operation must be applied iteratively – after each deletion step, frequencies are recomputed on the shortened string before the next step.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Iterative Node Cluster"

medium

WHY DOES IT MATTER?

Filtering by frequency is a fundamental pattern for data cleaning, deduplication, and noise reduction. Recognizing when an apparently iterative process collapses to a single pass prevents unnecessary complexity and performance penalties.

OPTIMIZATION CHALLENGE

The key insight is that removing unique elements does not affect the count of any other element, making the operation idempotent after the first sweep. This eliminates the need for repeated recomputation of frequencies.

REAL-WORLD CONNECTION

Think of a distributed log aggregation system that discards one‑off error messages (unique occurrences) to focus on recurring issues. Once the one‑off messages are filtered out, the remaining logs are stable and no further pruning is needed.

During an interview, first write a frequency map, then immediately construct the answer in a second pass. Mention the idempotence property to justify why a single iteration suffices; this demonstrates both correctness and optimality.

COMPLEXITY AT A GLANCE

⏱ Time:O(n)
💾 Space:O(1)

Core Theory — Why This Approach?

The problem reduces to a frequency‑filtering operation that can be solved in a single pass. By counting the occurrences of each character in the original string, we can immediately identify which characters have a frequency of exactly one. Removing those characters does not affect the frequencies of the remaining characters because only unique characters are eliminated; all other characters retain their original counts (which are ≥ 2). Consequently, after the first removal step the string already satisfies the termination condition, making further iterations unnecessary. This insight transforms an apparently iterative process into a straightforward linear scan.

A naive solution would repeatedly recompute the frequency map after each deletion, leading to O(n²) time in the worst case (e.g., a string where each iteration removes a single character). Such an approach also incurs extra overhead for rebuilding the string at every step. The optimal paradigm leverages a single frequency map (often an array of size 26 for lowercase letters) and a single pass to construct the final answer, achieving O(n) time and O(1) auxiliary space.

The underlying algorithmic pattern is a classic "filter by frequency" problem, akin to removing outliers in data streams. Recognizing that the operation’s idempotence eliminates the need for true iteration is the key theoretical breakthrough that drives the optimal solution.

Interview Questions on This Problem

Q1How would you modify the solution if the string could contain any Unicode characters, not just lowercase English letters?

Replace the fixed-size 26‑element array with a hash map (e.g., unordered_map<char,int>) to store frequencies. The rest of the algorithm stays the same: count frequencies, then build the result by keeping characters with count > 1. Time remains O(n) and space becomes O(k) where k is the number of distinct characters.

Q2Can you solve the problem in-place without using extra space proportional to the alphabet size?

Yes. Perform two passes: first, count frequencies using a 26‑element array (constant space). Second, use two pointers to overwrite the original string: one reads each character, the other writes it only if its frequency > 1. This modifies the string in place while still using O(1) extra space.

Q3Why does the iterative description not imply multiple passes, and how would you explain this to an interviewer?

Because only characters with frequency exactly one are removed, and removing them does not change the frequencies of any other character. After the first pass, every remaining character already has frequency ≥ 2, so the stopping condition is satisfied. Hence the process terminates after a single logical iteration.

Examples

Example 1

Input

abacabad

Output

ababa

Explanation: Initial frequencies: a=4, b=2, c=1, d=1. Characters c and d appear once, so they are removed, yielding "ababa". Re‑computing frequencies on "ababa" gives a=3, b=2; no character appears exactly once, so the process stops. The final string is "ababa".

Example 2

Input

abcde

Output

Explanation: All five characters appear exactly once. They are all removed in the first iteration, leaving an empty string. No further iterations are possible, so the answer is the empty string.

Example 3

Input

aabccdde

Output

aaccdd

Explanation: First pass frequencies: a=2, b=1, c=2, d=2, e=1. Characters b and e are unique and are deleted, producing "aaccdd". In the new string each character occurs twice, so no further deletions occur. The final string is "aaccdd".

Example 4

Input

zzxyyzz

Output

zzzz

Explanation: Initial frequencies: z=4, x=1, y=2. Character x is unique and is removed, resulting in "zzyyzz". New frequencies: z=4, y=2. No character has frequency one, so the algorithm stops. The resulting string is "zzzz" (the two y's were removed in the previous step because they became unique after x's removal).

Example 5

Input

mnoonm

Output

mnoonm

Explanation: Frequencies at the start: m=2, n=2, o=2. No character appears exactly once, therefore the string remains unchanged and is returned as‑is.

Constraints

  • 1 <= s.length <= 10^5
  • s consists only of lowercase English letters ('a'–'z')
  • The algorithm must run in O(n) time on average, where n is the length of the input string.

Optimal Approach & Strategy

Count frequencies once using a fixed-size array (or hash map), then construct the result by appending characters whose count exceeds one, achieving O(n) time and O(1) extra space.

Brute Force Approach

Repeatedly recompute the full frequency map after each deletion and rebuild the string until no character has frequency one, leading to O(n²) time in the worst case.

Verified Code Solutions

JavaScript Solution
Time: O(n)
function solution(nums) {
   let max_sum = nums[0];
   let current_sum = nums[0];
   for (let i = 1; i < nums.length; i++) {
       current_sum = Math.max(nums[i], current_sum + nums[i]);
       max_sum = Math.max(max_sum, current_sum);
   }
   return max_sum;
}

Asked in Top Tech Interviews

TCSPayPal

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.