Skip to content

Instantly share code, notes, and snippets.

@dluciano
Created September 20, 2022 19:44
Show Gist options
  • Save dluciano/95b70bc25dc7f70ca16e2dc75e7f8174 to your computer and use it in GitHub Desktop.
Save dluciano/95b70bc25dc7f70ca16e2dc75e7f8174 to your computer and use it in GitHub Desktop.
718. Maximum Length of Repeated Subarray
public class Solution {
public int FindLength(int[] nums1, int[] nums2) {
if(nums2.Length > nums1.Length)
(nums1, nums2) = (nums2, nums1);
var root = CreateTrie(nums1);
var maxLength = 0;
for(var i = 0; i < nums2.Length; ++i){
var current = root;
var subArrayLength = 0;
for(var j = i; j < nums2.Length; ++j){
var num = nums2[j];
if(!current.Children.ContainsKey(num)){
break;
}
current = current.Children[num];
subArrayLength++;
}
maxLength = Math.Max(maxLength, subArrayLength);
}
return maxLength;
}
private static Trie CreateTrie(int[] array){
var root = new Trie(new());
for(var i = 0; i < array.Length; ++i){
var current = root;
for(var j = i; j < array.Length; ++j){
var num = array[j];
if(current.Children.ContainsKey(num)){
current = current.Children[num];
continue;
}
var trie = new Trie(new());
current = current.Children[num] = trie;
}
}
return root;
}
record struct Trie(Dictionary<int, Trie> Children);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment