From f99831803176cc9058790b61e3756cd2bdc649be Mon Sep 17 00:00:00 2001 From: Kohei Asai Date: Mon, 30 Sep 2019 11:31:59 -0700 Subject: [PATCH] 160. Intersection of Two Linked Lists --- .../intersectionOfTwoLinkedLists.test.ts | 30 +++++++++++++++++++ solutions/intersectionOfTwoLinkedLists.ts | 18 +++++++++++ 2 files changed, 48 insertions(+) create mode 100644 solutions/intersectionOfTwoLinkedLists.test.ts create mode 100644 solutions/intersectionOfTwoLinkedLists.ts diff --git a/solutions/intersectionOfTwoLinkedLists.test.ts b/solutions/intersectionOfTwoLinkedLists.test.ts new file mode 100644 index 0000000..aa5a2e5 --- /dev/null +++ b/solutions/intersectionOfTwoLinkedLists.test.ts @@ -0,0 +1,30 @@ +import { + createSinglyLinkedListNode, + getNthNode +} from "../testUtilities/LinkedList"; +import { SinglyLinkedListNode } from "../types/LinkedList"; +import getIntersectionNode from "./intersectionOfTwoLinkedLists"; + +describe("160. Intersection of Two Linked Lists", () => { + const TEST_CASES: [any, number[], number[], number, number][] = [ + [8, [4, 1, 8, 4, 5], [5, 0, 1, 8, 4, 5], 2, 3], + [2, [0, 9, 1, 2, 4], [3, 2, 4], 3, 1], + [0, [2, 6, 4], [1, 5], 3, 2] + ]; + + for (const [, valuesA, valuesB, skipA, skipB] of TEST_CASES) { + const headA = createSinglyLinkedListNode(valuesA); + const headB = createSinglyLinkedListNode(valuesB); + let intersection: SinglyLinkedListNode | null = null; + + if (skipA < valuesA.length) { + intersection = getNthNode(headA!, skipA); + + getNthNode(headB!, skipB - 1).next = intersection; + } + + it(`returns the ${skipA}th node of "linked list A" when called with [${valuesA}], [${valuesB}], ${skipA} and ${skipB}`, () => { + expect(getIntersectionNode(headA, headB)).toBe(intersection); + }); + } +}); diff --git a/solutions/intersectionOfTwoLinkedLists.ts b/solutions/intersectionOfTwoLinkedLists.ts new file mode 100644 index 0000000..0fc2b63 --- /dev/null +++ b/solutions/intersectionOfTwoLinkedLists.ts @@ -0,0 +1,18 @@ +import { SinglyLinkedListNode } from "../types/LinkedList"; + +// 160. Intersection of Two Linked Lists +// https://leetcode.com/problems/intersection-of-two-linked-lists/ +export default function getIntersectionNode( + headA: SinglyLinkedListNode | null, + headB: SinglyLinkedListNode | null +): SinglyLinkedListNode | null { + let a = headA; + let b = headB; + + while (a !== b) { + a = a ? a.next : headB; + b = b ? b.next : headA; + } + + return a; +}