First Return to Origin
JavaScript
Medium
3 views
Problem Description
You get command string L,R,U,D. Find the earliest step (1-based) when position becomes (0,0) again. If never, print -1.
Input Format
One line command string.
Output Format
One integer step or -1.
Constraints
Length up to 2e5.
Official Solution
const fs=require('fs');const s=fs.readFileSync(0,'utf8').trim();let x=0,y=0;let ans=-1;for(let i=0;i<s.length;i++){const ch=s[i];if(ch==='L')x--;else if(ch==='R')x++;else if(ch==='U')y++;else if(ch==='D')y--;if(x===0&&y===0){ans=i+1;break;}}process.stdout.write(String(ans));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!