Hi,
Following is the question asked in the phone interview .
Given an array of characters, remove duplicate spaces
eg:
input : {'a', 'b', ' ', ' ', 'c' } Output : {'a', 'b', ' ', 'c'}
input : {'a', 'b', ' ', ' ', ' ' } Output : {'a', 'b', ' '}
My Approach 1 :
public List<Character> removeDupSpaces(List<Character> chars) {
List<Character> st = new ArrayList<Character>();
int count = 0;
for(Character c : chars) {
if(c != ' ') {
st.add(c);
} else {
count++;
if(count == 1){
st.add(c);
}
}
}
return st;
} My Approach 2 : Wanted to solve using 2 pointer approach without using extra space but not successfull :(
public void removeDupSpaces(List<Character> chars) {
int reader = 0;
int writer = 0;
int count = 0;
while(reader<chars.size()) {
if(chars.get(reader) != ‘ ‘) {
reader++;
writer++;
} else {
count ++;
reader++;
if(count > 1) {
writer++;
chars.set(writer, chars.get(reader));
chars.remove(chars.get(reader));
}
}
if(reader == chars.size()) { reader = 0};
}
}Any help would be appreciated.
Thanks