Hi All,
I was solving algorithm question from Hackerrank. I came across that you can't make a huge array in Java due to the limitation of memories.
►You will be given String s and int n.
String s = "aba" : or "a" or "abcab" .. anything.
int n = "10" : 1 <n <10¹²
Condition 1.
- The string 's' will be infinitely repeated until when it's length to reach to 'n'
Condition 2.
- Count how many letter 'a' come up in the string within 'n' length.
Example.
s : aba
n :10
abaabaabaa --> answer 7.
s: a
n: 10000000000000
aaa................aa --> answer 10000000000000.
Then how would you approach this problem?
I succeed in the first example, but won't be able to make the second example due to a limitation of the size of an array.
I can't think of the other way around not using arrays.
Following is my approach.
[HTML]
static long repeatedString(String s, long n) {
char[] array = s.toCharArray();
char[] resultArray = new char[(int) n];
int result = 0;
if(array.length < n){
int count = 0;
for(int i=0; i<resultArray.length; i++){
if(i < array.length ){
resultArray
= array;
} else {
resultArray = array[i % array.length];
}
if(resultArray == 'a') count++;
}
result = count;
} else {
int count = 0;
for (int i=0; i<array.length; i++){
if(array == 'a') count++;
}
result = count;
}
return result;
}
[/HTML]
https://www.hackerrank.com/challenges/repeated-string/problem