#3694

Distinct Points Reachable After Substring Removal

Medium
Hash TableStringSliding WindowPrefix SumHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Utilize prefix sums to track movements, allowing efficient calculation of reachable coordinates after removing any substring of length k.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create prefix sum arrays for x and y coordinates based on the moves in the string.
  2. 2Step 2: For each possible removal index, calculate the new final coordinates using the prefix sums.
  3. 3Step 3: Store the unique coordinates in a set and return its size.
solution.py12 lines
1def distinct_points_optimal(s, k):
2    n = len(s)
3    x_prefix, y_prefix = [0] * (n + 1), [0] * (n + 1)
4    for i in range(n):
5        x_prefix[i + 1] = x_prefix[i] + (1 if s[i] == 'R' else -1 if s[i] == 'L' else 0)
6        y_prefix[i + 1] = y_prefix[i] + (1 if s[i] == 'U' else -1 if s[i] == 'D' else 0)
7    unique_coords = set()
8    for i in range(n - k + 1):
9        x = x_prefix[n] - (x_prefix[i + k] - x_prefix[i])
10        y = y_prefix[n] - (y_prefix[i + k] - y_prefix[i])
11        unique_coords.add((x, y))
12    return len(unique_coords)

Complexity note: Prefix sums are computed in O(n) and each coordinate calculation is O(1), leading to O(n) overall.

  • 1Removing a substring affects the final coordinates based on the prefix sums.
  • 2Distinct final coordinates can be efficiently tracked using a set.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.