I recently solved a problem presented on https://www.geeksforgeeks.org/find-given-string-can-represented-substring-iterating-substring-n-times/
The problem is determining if a particular string can be represented from a substring by iterating the substring n times.
For example the string "abcabcabc"
can be represented by iterating the substring "abc"
3.
I came up with this Java solution
public static boolean canForm (String str) {
if(str.isEmpty()||str.length()==1) return true;
int end;
if (str.length()%2==0) {
end = str.length()/2;
} else {
end = (str.length()-1)/2;
}
for (int i=1; i<=end; i++) {
String s = str.substring(0,i);
String compare = "";
while (compare.length()<str.length()) {
compare += s;
}
if (compare.equals(str)) return true;
}
return false;
}
One condition of the problem is for the solution to be O(n). I concluded it was O(n) but I am unsure if my solution really is O(n) or it is in fact O(n^2) and why.