Merge the Tools! Python Hackerrank solution

Problem: Consider the following problem: You are given a string s and an integer k. Split s into n/k subsegments where each subsegment contains k ch
Admin

Problem:

Consider the following problem:

You are given a string s and an integer k. Split s into n/k subsegments where each subsegment contains k characters. Then, for each subsegment, delete any duplicate characters in the subsegment and print the subsegment without duplicates.

Example:

Input:

s = "AABCAAADA"

k = 3

Output:

AB

CA

AD

Explanation:

String s is split into n/k = 9/3 = 3 subsegments of length k=3:

AAB

CAA

ADA

The first subsegment is "AAB", which contains the duplicate characters "A". These are removed to produce the output "AB". The second subsegment is "CAA", which contains the duplicate character "A". This is removed to produce the output "CA". The third subsegment is "ADA", which contains no duplicate characters, so the output is "AD".

To solve this problem in Python, you can define a function that takes in the string s and integer k, and then implement the above algorithm to print the subsegments without duplicates.

Solution

def merge_the_tools(string, k):
    # your code goes here
    n = len(string)
    num_subsegments = n // k
    for i in range(num_subsegments):
        subsegment = string[i*k : (i+1)*k]
        unique_chars = []
        for char in subsegment:
            if char not in unique_chars:
                unique_chars.append(char)
                print(char, end="")
        print()

if __name__ == '__main__':
    string, k = input(), int(input())
    merge_the_tools(string, k)

The merge_the_tools function takes two arguments: a string string and an integer k. It first calculates the number of subsegments in the string by dividing the length of the string by k.

Then, it loops over each subsegment and creates a list unique_chars to store the unique characters in that subsegment. It iterates over each character in the subsegment and checks if it's already in the unique_chars list. If it's not, it adds it to the list and prints it. Finally, it prints a newline character to move to the next subsegment.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.