Dhaval Jardosh
Dhaval Jardosh

Reputation: 7299

Find words and put spaces after them

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

  1. Assume given a dictionary object containing all the words that can be in a string.
  2. 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?)

Upvotes: 0

Views: 230

Answers (2)

not_python
not_python

Reputation: 902

I have pseudo code.

words = Trie()
for word in dictionary:
    words. insert(word)

let str be the string.

let output be array
for char in string:
    words.walk(char)
    output.append(char)
    If words.isAtEndofWord() then
         output.append(' ')
         words.seek(0)

output = toString(output)

Trie is data structure to create dictionary. You can add functionality to walk with tree nodes unless it reaches end of a word.

Upvotes: 1

mcdowella
mcdowella

Reputation: 19601

This can be done with dynamic programming. Work through the array from left to right. Update an array of bits as you go to show whether there is a solution that ends at a given point. At each position consider all of the dictionary words that match a suffix of the text ending at that point. Look at the bit array and see if the text that would come just before a proposed word ends neatly. If so, set the bit for that position. When you get to the end, if it turns out there is a solution (final bit in bit-array set) work backwards from right to left, checking with the bit array to make sure that any word you chose leaves you in a position to find a solution for the portion of the text to the left of it.

(This solves the problem of finding possible matches with different lengths - if there is a chain of words that accounts neatly for all the text, this will find it)

Upvotes: 1

Related Questions