You are given a string commands consisting of the characters 'U', 'D', 'L' and 'R', representing directional movements (Up, Down, Left, Right) applied to a robot on an infinite 2D grid.
A command is considered redundant if it is immediately cancelled by the next command in the sequence. Specifically, a pair of adjacent commands is redundant when one is 'U' and the other is 'D', or one is 'L' and the other is 'R'. When such a redundant pair is found, both commands are removed from the sequence, and the commands that were on either side of it become adjacent and may form a new redundant pair that should also be removed. This process continues until no more redundant pairs remain.
Return the total number of commands removed from the original sequence.
Function Signature
def count_redundant_commands(commands: str) -> int:
Rules
-
A pair cancels in either order:
"UD"
and
"DU"
both cancel, as do
"LR"
and
"RL"
.
-
Two equal commands never cancel, and a vertical command never cancels a horizontal one (
"UL"
stays).
-
The final sequence is the same whatever order the redundant pairs are removed in, so the returned count is unique.
Constraints
-
1 <= commands.length <= 10^5
-
commands[i]
is one of
'U'
,
'D'
,
'L'
,
'R'
Examples
Input: commands = "UDLR"
Output: 4
'U' and 'D' cancel (2 removed), then 'L' and 'R' cancel (2 more removed). Nothing is left, so all 4 commands are removed.
Input: commands = "UULDDR"
Output: 0
The adjacent pairs are UU, UL, LD, DD and DR. None of them is U next to D or L next to R, so nothing is removed.
Input: commands = "RULRDD"
Output: 4
'L' and 'R' cancel, which leaves "RUDD". Now 'U' and the first 'D' are adjacent and cancel, leaving "RD", which has no redundant pair. 4 commands were removed.