Check 2 strings are following patterns

# Check 2 strings are following patterns

January 31, 2023

Name
Moch Lutfi
@kaptenupi

## Problem

Given an array strings, determine whether it follows the sequence given in the patterns array. In other words, there should be no i and j for which strings[i] = strings[j] and patterns[i] ≠ patterns[j] or for which strings[i] ≠ strings[j] and patterns[i] = patterns[j].

Example

• For strings = ["cat", "asu", "asu"] and patterns = ["a", "b", "b"], the output should be
solution(strings, patterns) = true;
• For strings = ["cat", "asu", "anjing"] and patterns = ["a", "b", "b"], the output should be
solution(strings, patterns) = false.

Input/Output

• [input] array.string strings

An array of strings, each containing only lowercase English letters.

Guaranteed constraints:
1 ≤ strings.length ≤ 10^5,
1 ≤ strings[i].length ≤ 10.

• [input] array.string patterns

An array of pattern strings, each containing only lowercase English letters.

Guaranteed constraints:
patterns.length = strings.length,
1 ≤ patterns[i].length ≤ 10.

• [output] boolean

Return true if strings follows patterns and false otherwise.

## Solution

• This solution uses two maps to store the relationship between a string and a pattern.
• For each string in strings, the solution checks if a pattern has already been assigned to that string and if the assigned pattern is the same as the current pattern in patterns.
• If not, the function returns false.
• The same is done for the pattern to string mapping.
• If no inconsistencies are found, the function returns true.

func solution(strings []string, patterns []string) bool {
stringToPattern := make(map[string]string)
patternToString := make(map[string]string)
for i, str := range strings {
pattern, strExists := stringToPattern[str]
string, patternExists := patternToString[patterns[i]]
if strExists && pattern != patterns[i] || patternExists && str != string {
return false
}
stringToPattern[str] = patterns[i]
patternToString[patterns[i]] = str
}
return true
}