Saturday, January 2, 2021

Construct string from another string

Problem: Given two strings say string1 and string2, check if string1 can be constructed from the string2. Each letter in the string2 can only be used once in string1. it is given that both strings contain only lowercase letters.

Example:

Input: string1 = "ab", string2 = "aab"
Output: true


Approach: It's very simple problem to solve. We can maintain a hash where key is string2 characters and value is the frequency of the characters in string2. 

Now while iterating through string1 if we find that any character is not found in hash or its count is 0, return false. If we reach till the end of string1, return true. 

Given that both string contain only lowercase letters, we can use array of size 26 for hashing.


Implementation in C#:

        public bool CanConstruct(string string1, string string2)

        {

            int[] string2Hash = new int[26];

            foreach (char ch in string2)

            {

                ++string2Hash[ch - 'a'];

            }

            foreach (char ch in string1)

            {

                if (string2Hash[ch - 'a'] == 0)

                {

                    return false;

                }

                --string2Hash[ch - 'a'];

            }

            return true;

        }


Complexity: O(n)

No comments:

Post a Comment