Once I was asked a question in an interview and I am still not clear how to solve it. Or couldn't even get close to it.
Q. Given is a of series of characters eg."thisisachallengingquestion", Write a program to put space after every word except the last one
Input : "thisisachallengingquestion"
Output: "this is a challenging question"
My Approach
- Assume given a dictionary object containing all the words that can be in a string.
- Traverse through all the letters with 2 pointers. Using the runner technique, keep on tracking the for actual word to match the key in object.
example:
Initially: Pointer 1 and Pointer 2 both are at index 0. Compares "t" in dictionary object key.(NO)
1st Iteration: "th" <- if this contains as key in dictionary object (NO)
2nd Iteration: "thi" (NO)
3rd Iteration: "this" (YES)
Push the word from 0th index to 3rd index in new Array and put space (" ") after it.
Place the 1st and 2nd pointer to the value of (2nd pointer + 1) and and so on till the length of the given string.
Please let me know if there is any better solution to this.
Questions can arise like:
1.Dictionary is not provided?
2.How can we do without using another Array?(Javascript allows dynamic array, so how can we use splice
or can we use splice
?)