{"id":7928,"date":"2025-07-16T11:28:48","date_gmt":"2025-07-16T05:58:48","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=7928"},"modified":"2025-07-17T20:54:21","modified_gmt":"2025-07-17T15:24:21","slug":"intersection-of-two-linked-list","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/intersection-of-two-linked-list\/","title":{"rendered":"Intersection of Two Linked Lists"},"content":{"rendered":"\n<link\n    href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.min.css\"\n    rel=\"stylesheet\"\n\/>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.min.js\"><\/script>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/plugins\/autoloader\/prism-autoloader.min.js\"><\/script>\n\n<style> \n.wp_blog_theme {\n  --primary: #E58C32;\n  --secondary: #f8c291;\n  --light-bg: #fef9f4;\n  --text-dark: #2d2d2d;\n  --tab-radius: 12px;\n  --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);\n  --code-bg: #001f3f;\n  --code-text: #d4f1ff;\n}\n\n.wp_blog_container {\n  font-family: 'Segoe UI', sans-serif;\n  background: var(--light-bg);\n  margin: 0;\n  padding: 0;\n  color: var(--text-dark);\n}\n\n\/* Heading *\/\n.wp_blog_main-heading {\n  text-align: center;\n  font-size: 2.4rem;\n  color: var(--primary);\n  margin-top: 2.5rem;\n  font-weight: bold;\n}\n\n\/* Explanation Card *\/\n.wp_blog_explanation,\n.wp_blog_code-tabs-container {\n  max-width: 940px;\n  margin: 2rem auto;\n  padding: 2rem;\n  background: white;\n  border-radius: var(--tab-radius);\n  box-shadow: var(--shadow);\n}\n\n\/* Text and Visuals *\/\n.wp_blog_explanation h2{\n  font-size: 1.4rem;\n  color: var(--primary);\n  margin-bottom: 0.5rem;\n}\n.wp_blog_explanation h5{\n  color: var(--primary);\n}\n\n.wp_blog_explanation p,\n.wp_blog_explanation li {\n  font-size: 1.05rem;\n  line-height: 1.7;\n  margin: 0.5rem 0;\n}\n.wp_blog_explanation code {\n  background: #f9cea6;\n  color: #2d2d2d;\n  padding: 3px 6px;\n  border-radius: 4px;\n  font-family: 'Courier New', monospace;\n}\n.wp_blog_explanation img {\n  max-width: 100%;\n  border-radius: var(--tab-radius);\n  margin-top: 1rem;\n  box-shadow: 0 2px 12px rgba(0,0,0,0.06);\n}\n\n\/* Tab Buttons *\/\n.wp_blog_code-tabs-header {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 0.5rem;\n  margin-bottom: 1rem;\n}\n.wp_blog_code-tab-button {\n  padding: 0.6rem 1.2rem;\n  border: 1px solid var(--primary);\n  background: white;\n  color: var(--primary);\n  border-radius: 50px;\n  font-weight: 600;\n  cursor: pointer;\n  transition: all 0.3s ease;\n}\n.wp_blog_code-tab-button:hover {\n  background: var(--secondary);\n}\n.wp_blog_code-tab-button.active {\n  background: var(--primary);\n  color: white;\n}\n\n\/* Code Content *\/\n.wp_blog_code-tab-content {\n  display: none;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n}\n.wp_blog_code-tab-content.active {\n  display: block;\n}\n.wp_blog_code-tab-content pre {\n  margin: 0;\n  padding: 1.5rem;\n  font-size: 1rem;\n  overflow-x: auto;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n  color: var(--code-text);\n}\n<\/style>\n\n<div class=\"wp_blog_container wp_blog_theme\"> \n    <h1 class=\"wp_blog_main-heading\"><\/h1>\n    <div class=\"wp_blog_explanation\">\n        <h2>Problem Statement:<\/h2>\n\n        <p>\n            Given the heads of two singly linked-lists <code>headA<\/code> and <code>headB<\/code>, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return <code>null<\/code>.\n        <\/p>\n\n        <p>For example, the following two linked lists begin to intersect at node <code>c1<\/code><\/p>\n        <!-- question image -->\n        <img decoding=\"async\" src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2025\/07\/Screenshot-2025-07-16-at-11.03.52\u202fAM.png\" alt=\"Stocks\" \/>\n\n        <p>The test cases are generated such that there are no cycles anywhere in the entire linked structure.<\/p>\n\n        <p><strong>Note<\/strong> that the linked lists must <strong>retain their original structure<\/strong> after the function returns.<\/p>\n\n        <p><strong>Custom Judge:<\/strong><\/p>\n            <p>The inputs to the <strong>judge<\/strong> are given as follows (your program is <strong>not<\/strong> given these inputs):<\/p>\n\n            <ul>\n                <li><code>intersectVal<\/code> &#8211; The value of the node where the intersection occurs. This is 0 if there is no intersected node.<\/li>\n                <li> <code>listA<\/code> &#8211; The first linked list.<\/li>\n                <li> <code>listB<\/code> &#8211; The second linked list.<\/li>\n                <li> <code>skipA<\/code> &#8211; The number of nodes to skip ahead in <code>listA<\/code> (starting from the head) to get to the intersected node.<\/li>\n                <li> <code>skipB<\/code> &#8211; The number of nodes to skip ahead in <code>listB<\/code> (starting from the head) to get to the intersected node.<\/li>\n            <\/ul>\n\n            <p>The judge will then create the linked structure based on these inputs and pass the two heads, <code>headA<\/code> and <code>headB<\/code> to your program. If you correctly return the intersected node, then your solution will be <strong>accepted<\/strong>.<\/p>\n\n            <h2>Examples<\/h2>\n            <h3> Example 1:<\/h3>\n                    <img decoding=\"async\" src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2025\/07\/Screenshot-2025-07-16-at-11.07.24\u202fAM.png\" alt=\"Stocks\" \/> \n                    \n                <p> <strong>Input: <\/strong>intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3<\/p>\n\n                <p> <strong>Output: <\/strong>Intersected at &#8216;8&#8217;<\/p>\n\n                <p><strong>Explanation: <\/strong>The intersected node&#8217;s value is 8 (note that this must not be 0 if the two lists intersect).\n                From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.\n                &#8211; Note that the intersected node&#8217;s value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory.\n                <\/p>\n\n            <h3> Example 2:<\/h3>\n                    <img decoding=\"async\" src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2025\/07\/ex_2.png\" alt=\"Stocks\" \/> \n                    \n                <p> <strong>Input: <\/strong>intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1<\/p>\n\n                <p> <strong>Output: <\/strong>Intersected at &#8216;2&#8217;<\/p>\n\n                <p><strong>Explanation: <\/strong>The intersected node&#8217;s value is 2 (note that this must not be 0 if the two lists intersect).\n                From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.\n                <\/p>\n            <h3> Example 3:<\/h3>\n                    <img decoding=\"async\" src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2025\/07\/ex_3.png\" alt=\"Stocks\" \/> \n                    \n                <p> <strong>Input: <\/strong>intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2<\/p>\n\n                <p> <strong>Output: <\/strong> No intersection<\/p>\n\n                <p><strong>Explanation: <\/strong>From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.\n                <\/p>\n                <p>\n                    Explanation: The two lists do not intersect, so return null.\n                <\/p>\n\n                <h2>Constraints:<\/h2>\n                <p>\n                    <ul>\n                        <li>The number of nodes of <code>listA<\/code> is in the <code>m<\/code>.<\/li>\n                        <li>The number of nodes of <code>listB<\/code> is in the <code>n<\/code>.<\/li>\n                        <li><code>1 <= m, n <= 3 * 10<sup>4<\/sup><\/code><\/li>\n                        <li><code>1 <= Node.val <= 10<sup>5<\/sup><\/code><\/li>\n                        <li><code>0 <= skipA <= m<\/code><\/li>\n                        <li><code>0 <= skipB <= n<\/code><\/li>\n                        <li><code>intersectVal<\/code> is 0 if <code>listA<\/code> and <code>listB<\/code> do not intersect.<\/li>\n                        <li><code>intersectVal == listA[skipA] == listB[skipB]<\/code> if <code>listA<\/code> and <code>listB<\/code>intersect.<\/li>\n                    <\/ul>\n                <\/p>\n                <p><strong>Follow up:<\/strong> Could you write a solution that runs in O(m + n) time and use only O(1) memory?<\/p>\n\n                <h2>Approach<\/h2>\n                <ul>\n                    <p>We use two pointers <code>pA<\/code> and <code>pB<\/code>, starting at <code>headA<\/code> and <code>headB<\/code>.<\/p>\n                    <li>Move both pointers one step at a time.<\/li>\n                    <li>When either pointer reaches the end, redirect it to the other list's head.<\/li>\n                    <li>If the lists intersect, the pointers will meet at the intersection node.<\/li>\n                    <li>If they don\u2019t intersect, both will eventually become <code>null<\/code> after traversing both lists.<\/li>\n                <\/ul>\n\n                <h2>Time Complexity:<\/h2>\n                <li>\n                  <p><strong>Time Complexity = O(n + m)<\/strong>\n                  <\/li>\n                <h2>Space Complexity:<\/h2>\n                <li>\n                  <p><strong>Space Complexity = O(1)<\/strong><\/p>\n                <\/li>\n\n<h2>Dry Run<\/h2> <div style=\"background: #f9f9f9; border-left: 4px solid var(--primary); padding: 1rem; border-radius: var(--tab-radius); margin: 1rem 0;\"> <p><strong>Input:<\/strong> <code>List A: 4 \u2192 1 \u2192 8 \u2192 4 \u2192 5, List B: 5 \u2192 6 \u2192 1 \u2192 8 \u2192 4 \u2192 5<\/code><\/p> <pre style=\"white-space: pre-wrap; background: #fff5ea; padding: 1rem; border-radius: 8px; overflow-x: auto;\">\npA = 4, pB = 5 \u2192 not equal\npA = 1, pB = 6 \u2192 not equal\npA = 8, pB = 1 \u2192 not equal\npA = 4, pB = 8 \u2192 not equal\npA = 5, pB = 4 \u2192 not equal\npA = null, pB = 5 \u2192 switch pA to headB\npA = 5, pB = null \u2192 switch pB to headA\npA = 6, pB = 4 \u2192 not equal\npA = 1, pB = 1 \u2192 not equal\npA = 8, pB = 8 \u2192 equal \u2192 exit loop\n<\/pre>\n\n<p><strong>Output:<\/strong> <code>Result: Node with value 8<\/code><\/p> <\/div>\n                \n        <h2>Visualisation:<\/h2>\n        <img decoding=\"async\" src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2025\/07\/Screenshot-2025-07-16-at-11.27.20\u202fAM.png\" alt=\"Stocks\" \/>\n    <\/div>\n\n    <div class=\"wp_blog_code-tabs-container\">\n        <div class=\"wp_blog_code-tabs-header\">\n            <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">JavaScript<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"cs\">C#<\/button>\n        <\/div>\n\n        <!-- JavaScript -->\n        <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n            <pre><code class=\"language-javascript\">\nvar getIntersectionNode = function(headA, headB) {\n    let pA = headA;\n    let pB = headB;\n\n    while(pA != pB) {\n        pA = pA == null ? headB : pA.next;\n        pB = pB == null ? headA : pB.next;\n    }\n    return pA;\n};\n     <\/code><\/pre>\n        <\/div>\n\n        <!-- Python -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n            <pre><code class=\"language-python\">\ndef getIntersectionNode(headA, headB):\n    pA = headA\n    pB = headB\n\n    while pA != pB:\n        pA = headB if pA is None else pA.next\n        pB = headA if pB is None else pB.next\n    return pA\n            <\/code><\/pre>\n        <\/div>\n\n        <!-- Java -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n            <pre><code class=\"language-java\">\npublic ListNode getIntersectionNode(ListNode headA, ListNode headB) {\n    ListNode pA = headA;\n    ListNode pB = headB;\n\n    while(pA != pB) {\n        pA = pA == null ? headB : pA.next;\n        pB = pB == null ? headA : pB.next;\n    }\n    return pA;\n}     <\/code><\/pre>\n        <\/div>\n\n        <!-- C++ -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n            <pre><code class=\"language-cpp\">\nListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {\n    ListNode* pA = headA;\n    ListNode* pB = headB;\n\n    while(pA != pB) {\n        pA = pA == nullptr ? headB : pA->next;\n        pB = pB == nullptr ? headA : pB->next;\n    }\n    return pA;\n}\n            <\/code><\/pre>\n        <\/div>\n\n        <!-- C -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n            <pre><code class=\"language-c\">\nstruct ListNode* getIntersectionNode(struct ListNode* headA, struct ListNode* headB) {\n    struct ListNode* pA = headA;\n    struct ListNode* pB = headB;\n\n    while(pA != pB) {\n        pA = pA == NULL ? headB : pA->next;\n        pB = pB == NULL ? headA : pB->next;\n    }\n    return pA;\n}\n            <\/code><\/pre>\n        <\/div>\n\n        <!-- C# -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"cs\">\n            <pre><code class=\"language-csharp\">\npublic ListNode GetIntersectionNode(ListNode headA, ListNode headB) {\n    ListNode pA = headA;\n    ListNode pB = headB;\n\n    while(pA != pB) {\n        pA = pA == null ? headB : pA.next;\n        pB = pB == null ? headA : pB.next;\n    }\n    return pA;\n}\n            <\/code><\/pre>\n        <\/div>\n    <\/div>\n<\/div>\n\n<script>\n    document.addEventListener(\"DOMContentLoaded\", () => {\n        const buttons = document.querySelectorAll(\".wp_blog_code-tab-button\");\n        const contents = document.querySelectorAll(\".wp_blog_code-tab-content\");\n\n        buttons.forEach((button) => {\n            button.addEventListener(\"click\", () => {\n                const lang = button.getAttribute(\"data-lang\");\n\n                buttons.forEach((btn) => btn.classList.remove(\"active\"));\n                contents.forEach((content) =>\n                    content.classList.remove(\"active\")\n                );\n\n                button.classList.add(\"active\");\n                document\n                    .querySelector(`.wp_blog_code-tab-content[data-lang=\"${lang}\"]`)\n                    .classList.add(\"active\");\n            });\n        });\n    });\n<\/script>\n","protected":false},"excerpt":{"rendered":"<p>Problem Statement: Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null. For example, the following two linked lists begin to intersect at node c1 The test cases are generated such that there are<\/p>\n","protected":false},"author":108,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[210,322,176,175,211,811,810,174,172,173],"tags":[],"class_list":{"0":"post-7928","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-algorithms","7":"category-algorithms-and-data-structures","8":"category-csharp","9":"category-cplusplus","10":"category-data-structures","11":"category-data-structures-and-algorithms","12":"category-dsa","13":"category-java","14":"category-javascript","15":"category-python"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7928","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/108"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=7928"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7928\/revisions"}],"predecessor-version":[{"id":7936,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7928\/revisions\/7936"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=7928"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=7928"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=7928"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}