why running time of this code is 0(n^2) [duplicate] - java

This question already has answers here:
What is the complexity of this simple piece of code?
(10 answers)
Closed 8 years ago.
why running time of this code is O(n^2).(as written in cracking the coding interview book).and how it could be improved
public String makeSentence(String[] words) {
StringBuffer sentence = new StringBuffer();
for (String w : words) sentence.append(w);
return sentence.toString();
}

For n = the number of elements in the words array
The for loop means at least O(n)
Inside the for loop, each instance of sentence.append(w) should be "constant" since sentence is a StringBuffer.
Doing constant things n times means you get a total of O(n)

The key line to look at is for (String w : words) sentence.append(w);
In Java, a String append is an O(n) operation. Because the append is inside the for loop, the method as a whole is O(n^2).

Related

Unsure about the time complexity of this code [duplicate]

This question already has answers here:
How can I find the time complexity of an algorithm?
(10 answers)
Closed 5 years ago.
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.
Your program runs in O(n^2), where n is propotional to the length of the string. Your code has a while loops that iterates n times in a for loop that iterates n times.
Hence the order of the program is O(n*n)=O(n^2).

Java count how many times a char from string occurs from an array [duplicate]

This question already has answers here:
How do I count the number of occurrences of a char in a String?
(48 answers)
Closed 5 years ago.
I'm new to java and I cant find the answer to this problem.
If I have two character arrays like this with counters:
Character[] abc = {'A','B','C'};
int countABC = 0;
Character[] def = {'D','E','F'};
int countDEF = 0;
And a string like this:
String something = "ABCDEFGHABAB";
How to increase the counters?
If you loop through each of the characters in the string and then within the loop use 2 'if' functions, one for each array then you can use the indexOf() function to search an array for that value. If the value is negative then it wasn't found and you don't increase the counter.
Here is some more info on indexOf():
https://www.tutorialspoint.com/java/java_string_indexof.htm

Find the longest String prefix [duplicate]

This question already has answers here:
Find longest common prefix?
(12 answers)
Closed 6 years ago.
Write a function to find the longest prefix of a list of string. For example,
['abc', 'abcde', 'abxyz'] => 'ab'
So it is an Arraylist and we find the longest prefix in the list of strings.
Let's try Java.
Please, no complete solutions
public string prefix (Arraylist<String> lst){
Arraylist<char[]> charLst = new Arraylist<>;
for(int i =0; i < lst.size(); i++){
charLst.add(lst.get(i).toCharArray());
}
}
But how do I proceed after creating a CharArray? This is already starting to be inefficient as it is O(n) with just the conversion to CharArray. I would just like some hint/help in the approach
Why do you add the ith character of every string to charLst? What you need is just the length of the longest common prefix, and then you can output the prefix based on the length you got.

count occurences of successive characters of a string [duplicate]

This question already has answers here:
Java compressing Strings
(21 answers)
Closed 7 years ago.
I have a String and I need to count occurances of successive characters of the string.
String s1="aabbcccaaa";
It should print output as
a2b2c3a3
String s1="aabbcccaaa";
char c[]=s1.toCharArray();
StringBuffer sb=new StringBuffer();
LinkedHashMap<Character,Integer> map=new LinkedHashMap<Character,Integer>();
for(int i=0;i<c.length;i++)
{
Character c1=c[i];
Integer frequency=map.get(c1);
map.put(c1, (frequency==null)?1:frequency+1);
if(map.size()>1 && c[i]!=c[i-1])
{
sb.append(c[i-1]+""+map.get(c[i-1]));
map.remove(c[i-1]);
}
}
sb.append(map);
System.out.println(sb);
I am not sure how i can achieve counts if same elements occur again.
Hint #1: Test the current character against the previous one.
Hint #2: Ask yourself, why do you need to use a Map?

Needs Logic explanation java reverse string [duplicate]

This question already has answers here:
How can I get a char array in reverse order?
(10 answers)
Closed 7 years ago.
Question of reverse string without using string function
I didn't get the inner for loop why s.length()-1 ? why -1 ?
its something have to do like multi dimensional arrays?
char ch[]=new char[s.length()];
for(i=0;i < s.length();i++)
ch[i]=s.charAt(i);
for(i=s.length()-1;i>=0;i--)
System.out.print(ch[i]);
found this code but
The indices of a Java String's characters go from 0 to the String's length - 1 (just like the indices of a Java array start in 0, so do the indices of a String).
Therefore in order to print the String in reverse order, the second loop iterates from s.length()-1 to 0. Prior to that, the first loop iterates from 0 to s.length()-1 in order to copy the characters of the String to a character array.
This has nothing to do with multi-dimensional arrays.
I know you asked for the iterative solution explanation. But, I'll give you the recursive explanation.
public static String reverse(String str)
{
if ((str == null) || (str.length() <= 1))
return str;
return reverse(str.substring(1)) + str.charAt(0);
}
Basically, you check every time the str before calling the function. This is called the base case and is used to stop when the job is completed and not get a stack overflow.
Then, afterwards, the functions returns just a section of the original function. At the end, you'll get the str completely reversed as the iterative solution.
Try using the function using System.out.println(reverse("hello"));

Categories