Python – Remove K length Duplicates from String
Last Updated :
02 Sep, 2020
Given a String remove all K length duplicates.
Input : test_str = ‘geeksforfreeksfo’, K = 3
Output : geeksforfree
Explanation : eek, eks, ksf, sfo already in string, hence removed.
Input : test_str = ‘geeksforg’, K = 3
Output : geeksforg
Explanation : No repeated string, nothing removed.
Method : Using loop + slicing
In this, we keep track of all the K length substrs encountered, extracted using slicing, and check each time for recurrence, if occurred they are removed.
Python3
test_str = 'geeksforfreeksfo'
print ( "The original string is : " + str (test_str))
K = 3
memo = set ()
res = []
for idx in range ( 0 , len (test_str) - K):
sub = test_str[idx : idx + K]
if sub not in memo:
memo.add(sub)
res.append(sub)
res = ''.join(res[ele] for ele in range ( 0 , len (res), K))
print ( "The modified string : " + str (res))
|
Output
The original string is : geeksforfreeksfo
The modified string : geeksforfree
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...