Feature #2: Merge Tweets In Twitter Feed
Explore how to merge two already sorted arrays of tweets to update a user's Twitter feed in chronological order. This lesson helps you implement an efficient algorithm using pointers, ensuring seamless integration of tweets from a newly followed user without extra space. Understand the time and space complexities involved to prepare for similar coding interview problems.
We'll cover the following...
Description
For the next feature, you have to implement a module that adds a user’s Tweets into an already populated Twitter feed in chronological order. Let’s assume that userA just started following userB. At this point, we want userB's Tweets to show up in userA's Twitter feed. We already have a chronologically sorted list of Tweets that will appear on userA's feed. Your job is to merge it with the list of userB's Tweets, which are also chronologically sorted.
As input, you will be given two sorted integer arrays, feed and tweets. The integers represent the posting time of the Tweets. You are also given the number of elements initialized in both of the arrays, which are m and n, respectively.
Note: Assume that
feedhas a size equal tom + nsuch that it has enough space to hold additional elements fromtweets.
Solution
We can solve this problem by comparing both arrays from the end and populating the result in the feed array. Take a look at the complete algorithm below:
-
First, we will initialize two pointers,
p1andp2, that point ...