Worst case scenario, there would be a recursive call of the second_word each time. The algorithm will compute two strings from scratch in each iteration of the loop. Recursively call this method with second_word as input and return true if it can be segmented
If second_word is in dictionary OR second_word is of zero length, then return true Second_word = substring (input string from index ) If you write the algorithm in steps it will be as follows: n = length of input stringįirst_word = substring (input string from index ) You can solve this problem by segmenting the large string at each possible position to see if the string can be completely segmented to words in the dictionary. Memory Complexity: Polynomial, O ( n 2 ) O(n^2) O ( n 2 ) Runtime Complexity: Exponential, O ( 2 n ) O(2^n) O ( 2 n ) Since it’s the first and only node in the merged list, it will also be the tail. Initially, the merged linked list is NULL.Ĭompare the value of the first two nodes and make the node with the smaller value the head node of the merged linked list. If there are still some elements in only one of the lists, you link this remaining list to the tail of the merged list. For all subsequent nodes in both lists, you choose the smaller current node and link it to the tail of the merged list, and moving the current pointer of that list one step forward.Ĭontinue this while there are some remaining elements in both the lists. Then choose the head of the merged linked list by comparing the first node of both linked lists. Maintain a head and a tail pointer on the merged linked list. Memory Complexity: Constant, O ( 1 ) O(1) O ( 1 ) Runtime Complexity: Linear, O ( m + n ) O(m + n) O ( m + n ) where m and n are lengths of both linked lists Click here to view the solution in C++, Java, JavaScript, and Ruby.