In this blog, we are going to solve a very popular hackerrank question which is called merge the tools. To solve this problem in O(n) time complexity we have used collections in python.
Problem Statement - https://www.hackerrank.com/challenges/merge-the-tools
Solution
from collections import OrderedDict
def merge_the_tools(string, k):
# your code goes here
i = 0
while i < len(string):
word1 = "".join(OrderedDict.fromkeys(string[i: i+k]))
print(word1)
i = i + k
if __name__ == '__main__':
string, k = input(), int(input())
merge_the_tools(string, k)
Steps followed to Solve the problem
- In this we used a collection of datatypes python known as an ordered dictionary.
- Ordered dictionary Return an instance of a
dict
subclass that has methods specialized for rearranging dictionary order. - It also removes all the repeatations in the string.
- Also in the top lines we have used string slicing to slice strings based on the parts needed.
Add a comment: