Skip to content

Two Sequences Two Pointers

Table of Contents

2540. Minimum Common Value

88. Merge Sorted Array

from typing import List


# Left Right Pointers
def merge(nums1: List[int], m: int, nums2: List[int], n: int) -> None:
    """Merges two sorted arrays in-place."""
    p1, p2, t = m - 1, n - 1, m + n - 1

    while p1 >= 0 or p2 >= 0:
        if p1 == -1:
            nums1[t] = nums2[p2]
            p2 -= 1
        elif p2 == -1:
            nums1[t] = nums1[p1]
            p1 -= 1
        elif nums1[p1] > nums2[p2]:
            nums1[t] = nums1[p1]
            p1 -= 1
        else:
            nums1[t] = nums2[p2]
            p2 -= 1

        t -= 1


nums1 = [1, 2, 3, 0, 0, 0]
m = 3
nums2 = [2, 5, 6]
n = 3
merge(nums1, m, nums2, n)
print(nums1)  # [1, 2, 2, 3, 5, 6]

2570. Merge Two 2D Arrays by Summing Values

1855. Maximum Distance Between a Pair of Values

1385. Find the Distance Value Between Two Arrays

from bisect import bisect_left
from typing import List


# Binary Search
def findTheDistanceValue(arr1: List[int], arr2: List[int], d: int) -> int:
    arr2.sort()
    res = 0

    for x in arr1:
        i = bisect_left(arr2, x - d)
        if i == len(arr2) or arr2[i] > x + d:
            res += 1

    return res


arr1 = [4, 5, 8]
arr2 = [10, 9, 1, 8]
d = 2
print(findTheDistanceValue(arr1, arr2, d))  # 2

925. Long Pressed Name

809. Expressive Words

2337. Move Pieces to Obtain a String

777. Swap Adjacent in LR String

844. Backspace String Compare

def backspaceCompare(s: str, t: str) -> bool:

    def build(text):
        stack = []

        for char in text:
            if char != "#":
                stack.append(char)
            elif stack:
                stack.pop()

        return "".join(stack)

    return build(s) == build(t)


print(backspaceCompare("ab#c", "ad#c"))  # True

986. Interval List Intersections

1537. Get the Maximum Score

244. Shortest Word Distance II

2838. Maximum Coins Heroes Can Collect

1229. Meeting Scheduler

1570. Dot Product of Two Sparse Vectors

1868. Product of Two Run-Length Encoded Arrays

Comments