Leetcode 2956. Find Common Elements Between Two Arrays
Given two integer arrays, find all the elements that appear in both arrays. The result should contain duplicates if they appear in both arrays, and it should be sorted. If there are no common elements, return an empty array.
#include <vector>
#include <algorithm>
#include <iostream>
std::vector<int> findCommonElements(std::vector<int>& nums1, std::vector<int>& nums2) {
// If either array is empty, return an empty array
if(nums1.empty() || nums2.empty())
return {};
// Sort both arrays
std::sort(nums1.begin(), nums1.end());
std::sort(nums2.begin(), nums2.end());
std::vector<int> result;
int i = 0, j = 0;
// Two-pointer technique to find common elements
while(i < nums1.size() && j < nums2.size()) {
if(nums1[i] == nums2[j]) {
result.push_back(nums1[i]);
i++;
j++;
} else if(nums1[i] < nums2[j]) {
i++;
} else {
j++;
}
}
return result;
}
int main() {
std::vector<int> nums1 = {1, 2, 2, 3, 4};
std::vector<int> nums2 = {2, 2, 3, 5};
std::vector<int> result = findCommonElements(nums1, nums2);
for (int num : result) {
std::cout << num << " ";
}
return 0;
}
This reasoning and the code should allow handling both large inputs and typical constraints you might encounter in coding interviews.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?