Similar Problems

Similar Problems not available

Number Of Times Binary String Is Prefix Aligned - Leetcode Solution

Companies:

LeetCode:  Number Of Times Binary String Is Prefix Aligned Leetcode Solution

Difficulty: Medium

Topics: array  

Problem statement:

Given a list of n binary strings, you need to find the number of times you can align the strings such that they all match the prefix of some other string in the list.

Solution:

  1. We will create a hashmap where keys will be binary strings and values will be their frequency of occurrence in the given list.

  2. Now for each string in the given list, we will check the number of times we can align it with another string in the list such that it matches the prefix of the other string.

  3. We will iterate over the string and compare its prefix with each string in the given list.

  4. If the prefix matches with some other string in the list, we will increment our count by the frequency of that string in the hashmap.

  5. Return the final count.

Time Complexity: O(n^2 * m) where n is the size of the given list and m is the maximum length of a string in the list. Here, we are comparing each string in the list with each other string in the list, hence O(n^2) and iterating over each character of each string in the list takes O(m) time.

Space Complexity: O(n) where n is the size of the given list. We are using a hashmap to store the frequency of each string in the list.

Code:

class Solution:
    def prefixAlignedStrings(self, strs: List[str]) -> int:
        count = 0        
        freq = {}  # hashmap to store frequency of each string in the given list
        
        # counting frequency of each string in the given list
        for s in strs:
            if s in freq:
                freq[s] += 1
            else:
                freq[s] = 1
        
        # iterating over each string in the given list and checking the alignment count
        for s in strs:
            for i in range(1, len(s)+1):
                prefix = s[:i]
                if prefix in freq:
                    count += freq[prefix]
        
        return count

Number Of Times Binary String Is Prefix Aligned Solution Code

1