418 Sentence Screen Fitting
Given arows x cols
screen and a sentence represented by a list of words, findhow many timesthe given sentence can be fitted on the screen.
Note:
A word cannot be split into two lines.
The order of words in the sentence must remain unchanged.
Two consecutive words
in a line
must be separated by a single space.
Total words in the sentence won't exceed 100.
Length of each word won't exceed 10.
1 ≤ rows, cols ≤ 20,000.
Example 1:
Example 2:
Example 3:
Brute Force
Learned something interesting this approach. Effectively, its just like using recursion: I can a function on itself a certain amount of times (iteratively), and update the parameters I pass into it. And just like recursion I have a stopping condition. I have found this approach to be a lot more intuitive than using recursion the traditional way.
The problem was broken down into a smaller subproblems: I look on how many times I can fit into a single row, and iterate through all the rows. This is not the quickest way, but it is definitely quicker than brute force. I suppose an optimization would be using division more effectively along with modulus.
I return the total_fit, which just gets added to a total of larger scope. In addition, I add the position of the iterator, which will be used on the next run. In
pos_end_row_and_amount_fit
, I entire that the row size is not exceeded, and add an additional fit once an entire loop of the sentence is iterated through.
Now with Dynammic Programming:
The Idea: We take a similiar approach from before except that we store our previously calculations into a map when we already know the answer. The approach goes as follows. Lets operate 1 row at a time, as keep track the total number of words that were fitted. So iterate through the number of rows. For each row, check how many words in the sentence we can fit inside the row starting at the word we left off. Store this into a dictionary. Every row operates independently, so we know that if we have the same word at the start of the row, the number of words that will fit will always be the same. To check how many words fit in a row, continually subtract the length of the next word - 1 (for space), until we reach a point where the number of remaining space in the current row is -2 or fewer. The reason for this is strictly for when I update the times
. -1 is acceptable because it implies that the space took the extra space when it already reached the final element of the row.
Complexity: Fluctuates dependent on input parameters. Maybe someone can help me here.
Last updated