Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Mohammed Dh Abbas
O(NL) Solution. Where N is the length of the input string text, and L is the length of each word in words.

Mohammed Dh Abbas

Jul 12, 2024

class Solution: def findWordConcatenation(self, text, words): result_indices = [] # List to store the starting indices of valid substrings word_len = len(words[0]) # Length of each word total_words = len(words) # Total number of words word_freq = {} # Hashmap to store word frequencies # Initialize word frequency hashmap for word in words: word_freq[word] = word_freq.get(word, 0) + 1 # Slide the window through the text for i in range(len(text) - total_words * word_len + 1): curr_window = text[i:i + total_words * word_len] # Current substring curr_word_count = {} # Hashmap to store word frequencies in the current window # Count word frequencies in the current window for j in range(0, total_words * word_len, word_len): curr_word = curr_window[j:j + word_len] curr_word_count[curr_word] = curr_word_count.get(curr_word, 0) + 1 # Check if the current window contains valid concatenated words if curr_word_count == word_freq: result_indices.append(i) return result_indices

0

0

Comments
Comments
G
gaspard01 5 months ago

O(NL) is possible, but your solution is still O(NML): your outer loop is O(N) and your inner loop is O(ML) because curr_word_count[curr_word] = curr_word_count.get(curr_word, 0) + 1 will hash curr_word which goes through each letter (L) and you do it M times.

On this page