1

I have a question which says

Given an input

ababacad 

The output should be all the a's should come first together rest characters should follow their sequence as they were originally. i.e.

aaaabbcd 

I solved it like below code

String temp="", first="" ; for(int i=0;i<str.length;i++) { if(str.charAt(i)!='a') temp=temp+str.charAt(i); else first=first+str.charAt(i); } System.out.print(first+temp); 

The output matches but it says it is still not optimised. I guess its already order of N complexity. Can it be optimised further.

13
  • 3
    Use StringBuilder instead of + on strings Commented Sep 10, 2019 at 16:40
  • 1
    yes..it has to do with both. Because strings are immutable, when you concatenate them together, you create a new string and copy the characters from each of the other strings into the new string. This overhead increases the amount of time your algorithm takes to run. Using StringBuilder instead will optimize your solution. Commented Sep 10, 2019 at 16:43
  • 1
    You clearly can't get a better asymptotic lower bound than linear simply because you must look at all the array elements to verify they're in an acceptable order. It might be possible to get better constant multipliers than your method yields, if that's what you're after. Commented Sep 10, 2019 at 16:46
  • 1
    @HimanshuAhuja is it a sorting problem? Does your solution works for ababadacabb? Commented Sep 10, 2019 at 16:53
  • 1
    The + makes it O(n^2). So, use a char array, swap values and return a new string from this char array. Commented Sep 10, 2019 at 19:54

1 Answer 1

1

Optimization here can mean string operations as well as the number of iterations. So, just to be on the safe side, you can implement it using arrays. The time complexity will be O(n) which is the minimum for this problem as you have to check every position for the presence of char 'a'.

String input = "ababacad"; char[] array = input.toCharArray(); char[] modified = new char[array.length]; int a = 0; // index for a int b = array.length - 1; // index for not a for (int i = array.length - 1; i >= 0; --i) { if (array[i] != 'a') modified[b--] = array[i]; else modified[a++] = array[i]; } String output = new String(modified); System.out.println(output); 
Sign up to request clarification or add additional context in comments.

1 Comment

You can also do it in-place, by reversing the loop, but the overall time complexity would be the same, while in terms of memory it would be constant.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.