Bolt | Online Assessment | Reverses the letters of words in a sentence
Anonymous User
549
Aug 02, 2022
Question
Write an algorithm which reverses the letters of words in a sentence, like:
Example input: I drive with Bolt
Example output: I evird htiw tloB
The input is a character array (not a string).
The function needs to work in-place, modifying the input array itself. So that memory consumption should be constant (e.g. temporary variables are allowed).
Don't use any extra arrays, string objects or language-provided functions/libraries.
Written tests for your solution are highly preferred.
Example in Java:
Input: char[] input = ['I',' ','d','r','i','v','e',' ','w','i','t','h',' ','B','o','l','t'];
public static char[] reverseWords(char [] input) {
/** write your code here */
return input;
}
Output: ['I',' ','e','v','i','r','d',' ','h','t','i','w',' ','t','l','o','B'];Solultion submitted (REJECTED)
public static char[] reverseWords(char [] input) {
Stack<Character> st = new Stack<>();
for(int i = 0 ; i < input.length; i++) {
if(input[i] != ' ') {
st.push(input[i]);
} else {
int index = i - st.size();
while(!st.empty()) {
input[index++] = st.pop();
}
}
}
int last = input.length - st.size();
while(!st.empty()) {
input[last++] = st.pop();
}
return input;
}- The solution which I submitted, I used Stack, but in worst case this would cause O(n) Space Complexity
- Is there any solution which can work in-place, modifying the input array itself. So that memory consumption should be constant ?
Comments (7)


