[LeetCode] Distinct Points Reachable After Substring Removal

3694. Distinct Points Reachable After Substring Removal

You are given a string s consisting of characters 'U', 'D', 'L', and 'R', representing moves on an infinite 2D Cartesian grid.

  • 'U': Move from (x, y) to (x, y + 1).
  • 'D': Move from (x, y) to (x, y - 1).
  • 'L': Move from (x, y) to (x - 1, y).
  • 'R': Move from (x, y) to (x + 1, y).

You are also given a positive integer k.

You must choose and remove exactly one contiguous substring of length k from s. Then, start from coordinate (0, 0) and perform the remaining moves in order.

Return an integer denoting the number of distinct final coordinates reachable.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
int distinctPoints(string s, int k) {
unordered_set<long long> mask;
long long y = 0, x = 0;
auto update = [&](int pos, int op) {
if(s[pos] == 'U') y += op;
if(s[pos] == 'D') y -= op;
if(s[pos] == 'R') x += op;
if(s[pos] == 'L') x -= op;
};

for(int i = 0; i < s.length(); i++) {
update(i,1);
if(i >= k) update(i-k,-1);
if(i + 1 >= k) {
long long bit = (abs(y)<<17) + abs(x);
if(y < 0) bit ^= 1ll<<37;
if(x < 0) bit ^= 1ll<<36;
mask.insert(bit);
}

}
return mask.size();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/10/11/PS/LeetCode/distinct-points-reachable-after-substring-removal/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.