Table of Contents
ToggleQuestion
- A string, s, of length n where s = c0c1. . . . cn-1.
- An integer, k, where k is a factor of n.
- The characters in ui are a subsequence of the characters in ti.
- Any repeat occurrence of a character is removed from the string such that each character in ui occurs exactly once. In other words, if the character at some index j in ti occurs at a previous index < j in ti, then do not include the character in string ui.
- string s: the string to analyze
- int k: the size of substrings to analyze
- 1 <= n <= 10^4, where n is the length of s
- 1 <= k <= n
- It is guaranteed that n is a multiple of k.
STDIN Function
----- --------
AABCAAADA s = 'AABCAAADA'
3 k = 3
AB
CA
AD
- t0 = “AAB” – u0 = “AB”
- t1 = “CAA” – u1 = “CA”
- t2 = “ADA” – u2 = “AD”
Solution
# the complete code as required for hackerrank challenge
def merge_the_tools(string, k):
split_string=(string[i:i+k] for i in range(0,len(string),k))
for i in split_string:
u=[]
u.append(i[0])
for j in range(1,len(i)):
if i[j] in u:
continue
else:
u.append(i[j])
print(''.join(str(e) for e in u))
if __name__ == '__main__':
string, k = input(), int(input())
merge_the_tools(string, k)
The merge_the_tools
function takes two parameters: string
(the input string) and k
(the length of each substring).
split_string
is created as a generator expression using a slice operation onstring
. It splitsstring
into substrings of lengthk
by iterating in steps ofk
from 0 to the length ofstring
.The loop
for i in split_string
iterates over each substring.Inside the loop, an empty list
u
is initialized to store the unique characters.The first character of the current substring
i
is appended tou
usingu.append(i[0])
.Another loop
for j in range(1, len(i))
starts from the second character of the current substring and iterates until the end.For each character
i[j]
in the current substring, it checks if it already exists inu
. If it does, it continues to the next iteration of the loop. Otherwise, it appends the character tou
.Finally,
print(''.join(str(e) for e in u))
is used to print the resulting subsequenceu
by joining the characters inu
together as a string.
If you find anything wrong in this Solution, feel free to reach us in the comment section.