Finding minimum deletions in string in JavaScript

When working with binary strings, we often need to ensure no two adjacent characters are the same. This requires finding the minimum number of deletions to create an alternating pattern.

Problem Statement

Given a binary string, we need to find the minimum deletions required so that no two adjacent characters are identical.

const str = '001001';
console.log("Original string:", str);
Original string: 001001

For the string '001001', we need 2 deletions to get '0101' (removing characters at indices 0 and 3).

Solution Approach

The algorithm iterates through the string and counts consecutive identical characters. Each time we find adjacent identical characters, we increment the deletion counter.

const minimumDeletions = (str = '') => {
    let count = 0;
    const { length } = str;
    
    for (let i = 0; i < length - 1; i++) {
        if (str[i] === str[i + 1]) {
            count++;
        }
    }
    
    return count;
};

// Test with multiple examples
const testStrings = ['001001', '1100', '101010', '0000'];

testStrings.forEach(str => {
    const deletions = minimumDeletions(str);
    console.log(`String: ${str} -> Deletions needed: ${deletions}`);
});
String: 001001 -> Deletions needed: 2
String: 1100 -> Deletions needed: 1
String: 101010 -> Deletions needed: 0
String: 0000 -> Deletions needed: 3

How It Works

The algorithm works by scanning through the string and counting each occurrence where str[i] === str[i + 1]. Each such occurrence represents one required deletion to break the consecutive pattern.

String: 001001 Index: 0 1 2 3 4 5 Chars: 0 0 1 0 0 1 Del 1 Del 2 Result: 0101 (2 deletions)

Alternative Implementation

Here's a more explicit version that shows which characters would be deleted:

const minimumDeletionsDetailed = (str = '') => {
    let count = 0;
    let result = [];
    
    for (let i = 0; i < str.length - 1; i++) {
        if (str[i] === str[i + 1]) {
            count++;
            result.push(`Delete char at index ${i + 1} (${str[i + 1]})`);
        }
    }
    
    return {
        deletions: count,
        operations: result
    };
};

const detailed = minimumDeletionsDetailed('001001');
console.log('Deletions needed:', detailed.deletions);
console.log('Operations:', detailed.operations);
Deletions needed: 2
Operations: [ 'Delete char at index 1 (0)', 'Delete char at index 4 (0)' ]

Time and Space Complexity

Metric Complexity Description
Time O(n) Single pass through string
Space O(1) Only counter variable used

Conclusion

The minimum deletions algorithm efficiently solves the problem in linear time by counting adjacent identical characters. This approach ensures the resulting string has no consecutive duplicate characters with minimal deletions.

Updated on: 2026-03-15T23:19:00+05:30

216 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements