LeetCode 1213: Intersection of Three Sorted Arrays Solution

Master LeetCode problem 1213 (Intersection of Three Sorted Arrays), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1213. Intersection of Three Sorted Arrays

Problem Explanation

Explanation:

To find the intersection of three sorted arrays, we can iterate through all three arrays simultaneously. We maintain three pointers pointing to the current element in each array. At each step, we compare the current elements pointed by the three pointers. If the elements are equal, we add it to the result as it is an intersection. If the elements are not equal, we move the pointer of the array with the smallest element to the next element. We continue this process until we reach the end of any of the arrays.

Time complexity: O(n), where n is the total number of elements in the three arrays combined. Space complexity: O(1)

:

Solution Code

import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<Integer> arraysIntersection(int[] arr1, int[] arr2, int[] arr3) {
        List<Integer> result = new ArrayList<>();
        int p1 = 0, p2 = 0, p3 = 0;

        while (p1 < arr1.length && p2 < arr2.length && p3 < arr3.length) {
            if (arr1[p1] == arr2[p2] && arr2[p2] == arr3[p3]) {
                result.add(arr1[p1]);
                p1++;
                p2++;
                p3++;
            } else if (arr1[p1] < arr2[p2]) {
                p1++;
            } else if (arr2[p2] < arr3[p3]) {
                p2++;
            } else {
                p3++;
            }
        }

        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1213 (Intersection of Three Sorted Arrays)?

This page provides optimized solutions for LeetCode problem 1213 (Intersection of Three Sorted Arrays) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1213 (Intersection of Three Sorted Arrays)?

The time complexity for LeetCode 1213 (Intersection of Three Sorted Arrays) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1213 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1213 in Java, C++, or Python.

Back to LeetCode Solutions