1. Two-Pointer Merge
Intuition
Advance two pointers i and j. Increment a counter until the kth element is reached.
When to apply: Basic baseline check.
Algorithm
- Step 1: i = 0, j = 0, count = 0, ans = -1.
- Step 2: While i < n and j < m: pick smaller, count++. If count == k, return element.
- Step 3: Exhaust remaining elements in arr1 or arr2.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; int kthElement(vector<int>& arr1, vector<int>& arr2, int k) { int n = arr1.size(), m = arr2.size(); int i = 0, j = 0, count = 0, ans = -1; while (i < n && j < m) { if (arr1[i] <= arr2[j]) { ans = arr1[i++]; } else { ans = arr2[j++]; } count++; if (count == k) return ans; } while (i < n) { ans = arr1[i++]; count++; if (count == k) return ans; } while (j < m) { ans = arr2[j++]; count++; if (count == k) return ans; } return ans;} int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(k)— Takes k pointer increments. - Space complexity:
O(1)— O(1) extra space.