Showing posts with label data filtering. Show all posts
Showing posts with label data filtering. Show all posts

Sunday, September 8, 2024

Removing Consecutive Duplicates from a String

String Processing: Remove Spaces & Condense Characters

String Processing: Remove Spaces & Condense Characters

You have a string consisting of various characters, including letters and dots, separated by spaces. The goal is to process this string to:

  • Remove all spaces
  • Condense consecutive duplicate characters into a single instance
  • Output the condensed characters as a continuous string

Solution Overview

1. Remove Spaces

Start by creating a list of characters from the string while ignoring any spaces. This step effectively filters out all the spaces, leaving only the non-space characters.

2. Condense Duplicates

Traverse the filtered list and remove consecutive duplicate characters. Only the first occurrence of each sequence is retained.

3. Output the Result

After condensing, output the characters as a continuous string without separators.

Step-by-Step Breakdown

Step 1: Filter Out Spaces

From the original string, extract all characters that are not spaces. This gives a list containing only relevant characters.

Step 2: Remove Consecutive Duplicates

Create a new list starting with the first character. Compare each character with the previous one and keep it only if it differs.

Step 3: Print the Result

Iterate through the condensed list and print each character consecutively.

Example CLI Output


Input:
a a a . . . b b c c . .

Processing:
- Remove spaces
- Condense duplicates

Output:
a.bc.

Python Implementation


s = "a a a . . . b b c c . ."

filtered = [c for c in s if c != " "]

result = [filtered[0]]
for c in filtered[1:]:
    if c != result[-1]:
        result.append(c)

print("".join(result))

๐Ÿ’ก Key Takeaways

  • Simplify input before processing
  • Adjacent comparison removes redundancy efficiently
  • Linear-time solutions scale well
  • Technique applies to logs, streams, and compression
Interactive HTML learning view • High contrast • Readable everywhere

Featured Post

How HMT Watches Lost the Time: A Deep Dive into Disruptive Innovation Blindness in Indian Manufacturing

The Rise and Fall of HMT Watches: A Story of Brand Dominance and Disruptive Innovation Blindness The Rise and Fal...

Popular Posts