HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Finding the minimum number of required deletions to have a non-repeating string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
numberthenonhavedeletionsrepeatingminimumfindingstringrequired

Problem

I wrote code for the following problem:


Given a string, print out the number of deletions required so that the adjacent alphabets are distinct.

Please suggest different methods by which I can increase the speed of execution.

tst = int(input())
for i in range(0,tst):
    str = input()
    length = len(str)
    str = list(str)
    j=0;
    count = 0
    while(j<length):
       if(j+1<length):
            if((str[j] == str[j+1])):
                del str[j+1]
                count+=1
                length-=1
            else:
                j+=1
       else:
            j+=1
    print(count)

Solution

Here's your culprit:

del str[j+1]


When you remove one character from a string, all subsequent characters need to be shifted into the hole that you create. That changes your algorithm from O(Length) to a worst-case scenario of O(Length2), if every character is the same.

Additionally, your inner loop looks a lot like C code. Here is one way to reformulate it.

def count_consecutive_deletions(s):
    deletions = 0
    for i in range(1, len(s)):
        if s[i] == s[i - 1]:
            deletions += 1
    return deletions

def testcases():
    for _ in range(int(input())):
        yield input()

for case in testcases():
    print(count_consecutive_deletions(case))

Code Snippets

del str[j+1]
def count_consecutive_deletions(s):
    deletions = 0
    for i in range(1, len(s)):
        if s[i] == s[i - 1]:
            deletions += 1
    return deletions

def testcases():
    for _ in range(int(input())):
        yield input()

for case in testcases():
    print(count_consecutive_deletions(case))

Context

StackExchange Code Review Q#77120, answer score: 6

Revisions (0)

No revisions yet.