Wednesday, 10 May 2017

Compressing a String - An Amazon Problem



Problem Statement
Compress a given string "aabbbccc" to "a2b3c3" constraint: inplace compression, no extra space to be used  assumption : output size will not exceed input size.. ex input:"abb" -> "a1b2" buffer overflow.. such inputs will not be given.
Solution : 
Since no extra is to be use hence we can't use recursion in this case . we need to operate on array to make the operation in place . lets see a simple solution to this problem though many ways of doing it possible so one of them I am mentioning here : 
public  static String compressString(String input){
/*
* @sachin srivastava
* tek9g.blogspot.com
* */
StringBuilder sb = new StringBuilder();
if(input == null || input.isEmpty()){
return null;
} else if(input.length() <= 2){
return input;
}
char[] ch = input.toCharArray();
int lenght = ch.length;
int count = 1;
for (int i = 0; i <=lenght-1; i++) {
if(i!=lenght-1 && ch[i] == ch[i+1] ){
count++;
} else {
sb.append(ch[i] + "" +count);
count = 1;
}
}
if(input.length() < sb.toString().length()){
System.out.println("invalid input buffer overflow");
}
return sb.toString();
}

Input1 : aaaaaaaabbcccccccgggggggaaaaaaaeeeeeef

Output1 : a8b2c7g7a7e6f1
Input2 :  abb
Output : invalid input buffer overflow

a1b2

Input3 : abbrrrrtttttgggaaawwww

Output3 : a1b2r4t5g3a3w4

Time Complexity : O(n)
Space Complexity : O(1)  -- in place 

Enjoy coding !!!!


No comments:

Post a Comment