diff --git a/intersection-of-two-linked-lists/sol.go b/intersection-of-two-linked-lists/sol.go new file mode 100644 index 0000000..39d3a8e --- /dev/null +++ b/intersection-of-two-linked-lists/sol.go @@ -0,0 +1,29 @@ +package main + +type ListNode struct { + Val int + Next *ListNode +} + +// O(n+m) time and O(n) memory solution +// Only iterates over each list once, unlike +// the other solution which iterates twice. +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func getIntersectionNode(headA, headB *ListNode) *ListNode { + exists := map[*ListNode]bool{} + for current := headA; current != nil; current = current.Next { + exists[current] = true + } + for current := headB; current != nil; current = current.Next { + if exists[current] { + return current + } + } + return nil +} diff --git a/intersection-of-two-linked-lists/sol_O(1)_mem.go b/intersection-of-two-linked-lists/sol_O(1)_mem.go new file mode 100644 index 0000000..dd643af --- /dev/null +++ b/intersection-of-two-linked-lists/sol_O(1)_mem.go @@ -0,0 +1,43 @@ +package main + +type ListNode struct { + Val int + Next *ListNode +} + +// O(n + m) time and O(1) memory solution +// Gets the length of each list, then +// lines them up and searches for equal +// nodes. +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func getIntersectionNode(headA, headB *ListNode) *ListNode { + len1, len2 := getLen(headA), getLen(headB) + diff := len1 - len2 + for diff > 0 { + headA = headA.Next + diff-- + } + for diff < 0 { + headB = headB.Next + diff++ + } + for headA != headB { + headA = headA.Next + headB = headB.Next + } + return headA +} + +func getLen(head *ListNode) int { + len := 0 + for current := head; current != nil; current = current.Next { + len++ + } + return len +}