3 min to read
Merge the Tools! - HackerRank Python Solution
Merge the Tools! is a medium-difficulty problem that involves string manipulation. We will learn how to solve this problem in Python through a step-by-step tutorial.
Disclaimer: We encourage you to solve this challenge yourself before reading our tutorial. We have provided a detailed explanation of the problem and our solutions to help you check your work.
Problem Statement
Merge the Tools! is a medium-difficulty problem that involves string manipulation. The problem statement is as follows. String s
of length n
is composed of English letters. We have to divide the input string into n/k
substrings where each substring contains k
characters.
Input Format:
- The first line contains a single string,
s
. - The second line contains an integer,
k
, where k is the factor ofn
.n
is the length of the strings
.
Output Format:
- Print
n/k
lines where each line has thek
unique characters from strings
.
We have to divide the string into n/k
substrings where each substring contains k
characters. We have to remove any subsequent occurrences of non-distinct characters in each substring.
For example, the given string is AABCAAADA
and the k is 3.
The string is broken into 3 substrings and the characters of each substring should be distinct.
AAB
CAA
ADA
As we can see the first substring is AAB
and the characters are A
and B
. The second substring is CAA
and the characters are C
and A
. The third substring is ADA
and the characters are A
and D
.
We have to print each substring on a new line after removing the duplicate characters then the final output will be.
AB
CA
AD
Merge the Tools Solution in Python
Explanation of Solution
- The merge_the_tools() function takes two arguments: the string string and the integer k.
- The function first iterates over the string string in steps of k.
- For each step, the function creates a substring of length k starting from the current position in the string.
-
The function then sorts the characters in the substring using the sorted() function. The sorted() function takes a list as its argument and sorts it in ascending order.
-
The function then removes any duplicate characters from the substring using the set() function. The set() function takes a list as its argument and returns a set containing the unique elements of the list in index order.
-
The function then joins the characters in the substring using the join() function. The join() function takes a list as its argument and returns a string containing the elements of the list joined by the separator string.
- The main() function is responsible for getting the input from the user and calling the merge_the_tools() function. The function first gets the string string and the integer k from the user. Then, it calls the merge_the_tools() function to merge the tools in the string and print the result.