DEV Community 👩‍💻👨‍💻

Cover image for Merge the Tools! Solution | HackerRank | Python

Merge the Tools! Solution | HackerRank | Python

The Problem

Consider the following:

  • n is a length of a string s.
  • k is a factor of n.

We can split s into nk\frac n k substrings where each subtring, tit_i , consists of a contiguous block of k characters in s. Then, use each tit_i to create string uiu_i such that:

  • The characters in uiu_i are a subsequence of the characters in tit_i .
  • Any repeat occurrence of a character is removed from the string such that each character in uiu_i occurs exactly once. In other words, if the character at some index j in tit_i occurs at a previous index < j in tit_i , then do not include the character in string uiu_i .

Given s and k, print nk\frac n k lines where each line i denotes string uiu_i .

Print each subsequence on a new line. There will be nk\frac n k of them. No return value is expected.

The Input

  • The first line contains a single string, s.
  • The second line contains an integer, k, the length of each substring.

Constraints

  • 1≤n≤1041 \le n \le 10^4 , where n is the length of s
  • 1≤k≤n1 \le k \le n
  • It is guaranteed that n is a multiple of k.

Sample:

AABCAAADA
3
Enter fullscreen mode Exit fullscreen mode

The Output

Sample:

AB
CA
AD
Enter fullscreen mode Exit fullscreen mode

Explanation

Split s into nk=93=3\frac n k = \frac 9 3 = 3 equal parts of length k = 3. Convert each tit_i to uiu_i by removing any subsequent occurrences of non-distinct characters in tit_i :

  1. t0=“AAB”→u0=“AB”t_0 = \text{\textquotedblleft} AAB \text{\textquotedblright} \rightarrow u_0 = \text{\textquotedblleft} AB \text{\textquotedblright}
  2. t1=“CAA”→u1=“CA”t_1 = \text{\textquotedblleft} CAA \text{\textquotedblright} \rightarrow u_1 = \text{\textquotedblleft} CA \text{\textquotedblright}
  3. t2=“ADA”→u2=“AD”t_2 = \text{\textquotedblleft} ADA \text{\textquotedblright} \rightarrow u_2 = \text{\textquotedblleft} AD \text{\textquotedblright}

Print each uiu_i on a new line.

The Solution

The Code

Source Code 1

def merge_the_tools(string, k):
    l = len(string)//k
    for i in range(l):
        print(''.join(dict.fromkeys(string[i*k:(i*k)+k])))
Enter fullscreen mode Exit fullscreen mode

Source Code 2

from collections import OrderedDict as od

def merge_the_tools(string, k):
    l = len(string)//k
    for i in range(l):
        print(''.join(od.fromkeys(string[i*k:(i*k)+k])))
Enter fullscreen mode Exit fullscreen mode

Original Source

Let's be friend 👋

Top comments (0)

DEV

Thank you.

 
Thanks for visiting DEV, we’ve worked really hard to cultivate this great community and would love to have you join us. If you’d like to create an account, you can sign up here.