Ninja has been given a string ‘WORD’ containing lower case alphabets. Ninja wants to know all the strings by dividing ‘WORD’ into ‘N’ strings of equal length.
For Example:
For ‘WORD’ = “abcdefgh”, ‘N’ = 2. Following are the 2 strings of length 4.
“abcd”
“efgh”
Can you help Ninja to get all the strings from ‘WORD’ by dividing them into equal parts?
The first line of input contains an integer 'T' which denotes the number of test cases or queries to be run. Then the test cases follow.
The first line of each test case contains a string ‘WORD’ and an integer ‘N’.
Output Format :
For each test case, print all strings that can be formed from ‘WORD’ by dividing it into ‘N’ equal parts.
Return empty string array/list if it is not possible to divide ‘WORD’ into ‘N’ equal length strings.
Print the output of each test case in a separate line.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
1 <= ‘T’ <= 100
‘WORD’ = Lower case english alphabet
1 <= |WORD| <= 2000
1 <= ‘N’ <= |WORD|
Time Limit: 1 second
2
asdfghjkl 3
codingninjas 5
asd fgh jkl
For the first test case:
Given ‘WORD’ = “asdfghjkl” can be divided into 3 strings each of length 3.
Following are the possible strings of length 3.
1. “asd”
2. “fgh”
3. “jkl”
For the second test case:
Given ‘WORD’ = “codingninjas”, it is impossible to divide this ‘WORD’ into 5 strings of equal length.
So we return an empty array/list.
2
a 1
code 4
a
c o d e
Try to use the brute force approach to generate all strings.
First, check if the ‘WORD’ can be divided into ‘N’ strings of equal length or not.
Calculate the possible length ‘len’ of ‘N’ equal length strings.After getting the length, iterate the ‘WORD’ and for each substring of length ‘len’ starting from index 0 print the substring.
Here is the complete Algorithm:
O(|WORD|), where |WORD| is the length of the string ‘WORD’.
Because in the worst case we are iterating each character of the ‘WORD’ exactly once. Hence the overall time complexity will be |WORD|.
O(1).
Because we are not using any extra space.