If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To find the common elements in three sorted arrays, you can use a three-pointer approach. Here's the algorithm to achieve this:
- Initialize three pointers
ptr1,ptr2, andptr3, each pointing to the beginning of each array (index 0).- While all three pointers are within the array bounds: a. If the elements at all three pointers are equal, add the element to the result vector and increment all three pointers. b. If the element at
ptr1is smaller than the elements atptr2andptr3, incrementptr1. c. If the element atptr2is smaller than the elements atptr1andptr3, incrementptr2. d. If the element atptr3is smaller than the elements atptr1andptr2, incrementptr3.- Continue until any one of the pointers reaches the end of its respective array.
Here's the C++ code to find the common elements in three sorted arrays:
cppCopy code
#include <iostream> #include <vector> std::vector<int> findCommonElements(std::vector<int>& nums1, std::vector<int>& nums2, std::vector<int>& nums3) { std::vector<int> result; int ptr1 = 0, ptr2 = 0, ptr3 = 0; while (ptr1 < nums1.size() && ptr2 < nums2.size() && ptr3 < nums3.size()) { if (nums1[ptr1] == nums2[ptr2] && nums2[ptr2] == nums3[ptr3]) { result.push_back(nums1[ptr1]); ptr1++; ptr2++; ptr3++; } else if (nums1[ptr1] <= nums2[ptr2] && nums1[ptr1] <= nums3[ptr3]) { ptr1++; } else if (nums2[ptr2] <= nums1[ptr1] && nums2[ptr2] <= nums3[ptr3]) { ptr2++; } else { ptr3++; } } return result; } int main() { std::vector<int> nums1 = {1, 5, 10, 20, 40, 80}; std::vector<int> nums2 = {6, 7, 20, 80, 100}; std::vector<int> nums3 = {3, 4, 15, 20, 30, 70, 80, 120}; std::vector<int> commonElements = findCommonElements(nums1, nums2, nums3); if (!commonElements.empty()) { std::cout << "Common elements in three sorted arrays:"; for (int element : commonElements) { std::cout << " " << element; } std::cout << std::endl; } else { std::cout << "No common elements found." << std::endl; } return 0; }Example Output:
pythonCopy code
Common elements in three sorted arrays: 20 80In this code, the
findCommonElementsfunction finds the common elements using the three-pointer approach. The time complexity of this approach is O(n), where n is the total number of elements in the three arrays.

I bought this course, it worth it!

Hi i want to buy this course but you dont have master card payment method please let me know how i can buy it

Dear mk.info.work, Now we have all types of payment options. If you need to purchase just checkout our official website
Quick answers to common questions about our courses, quizzes, and learning platform
Didn't find what you're looking for?
Contact Support
SCIAKU Team please upload 1st video of TREE please please please, please