Every post has an "activity pub id" (ap_id in the api) which is a URL to the post on its home instance. Every Lemmy instance can get a link to a post by its activity pub id.
The flow is:
parse the URL and get the numerical ID
call an api endpoint with post details (on the instance the link points to), which includes its activity pub id
call an api endpoint on your target instance to resolve the activity pub id to a local post (which includes its local ID)
construct a new URL in the form of https://[targetInstance]/post/[localID]