🚀 LeetCode Day Problem Solving 🚀 Day-39 📌 Problem: A robot starts at position (0, 0) on a 2D plane. You are given a string moves representing its movement sequence. Each character in the string denotes a move: ➡ 'R' → Right ⬅ 'L' → Left ⬆ 'U' → Up ⬇ 'D' → Down 👉 Your task is to determine whether the robot returns to the origin (0, 0) after completing all moves. Return true if it returns to origin, otherwise false. 🧠 Example 1: Input: moves = "UD" ✅ Output: true 📖 Explanation: Move Up → (0, 1) Move Down → (0, 0) ✔ Robot returns to origin 🧠 Example 2: Input: moves = "LL" ❌ Output: false 📖 Explanation: Move Left → (-1, 0) Move Left → (-2, 0) ❌ Robot does not return to origin 💡 Key Insight: ✔ Count movements: Number of 'U' should equal 'D' Number of 'L' should equal 'R' ✔ OR simulate coordinates: Track (x, y) position 📊 Complexity Analysis: ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) 🧠 What I Learned: ✔ Simple simulation problems can be solved efficiently ✔ Importance of balancing movements ✔ Good practice for coordinate tracking ✅ Day 39 Completed 🚀 Keep going strong with DSA & consistency 💪 #Leetcode #DSA #ProblemSolving #BitManipulation #CodingJourney #InterviewPreparation #Consistency #MilanSahoo 🚀
Robot Returns to Origin After Moves
More Relevant Posts
-
🚀 #LeetCode Day Problem Solving 🚀 Day-20 📌 Problem: A robot starts at position (0, 0) on a 2D plane. You are given a string moves representing its movement sequence. Each character in the string denotes a move: ➡ 'R' → Right ⬅ 'L' → Left ⬆ 'U' → Up ⬇ 'D' → Down 👉 Your task is to determine whether the robot returns to the origin (0, 0) after completing all moves. Return true if it returns to origin, otherwise false. 🧠 Example 1: Input: moves = "UD" ✅ Output: true 📖 Explanation: Move Up → (0, 1) Move Down → (0, 0) ✔ Robot returns to origin 🧠 Example 2: Input: moves = "LL" ❌ Output: false 📖 Explanation: Move Left → (-1, 0) Move Left → (-2, 0) ❌ Robot does not return to origin 💡 Key Insight: ✔ Count movements: Number of 'U' should equal 'D' Number of 'L' should equal 'R' ✔ OR simulate coordinates: Track (x, y) position 📊 Complexity Analysis: ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) 🧠 What I Learned: ✔ Simple simulation problems can be solved efficiently ✔ Importance of balancing movements ✔ Good practice for coordinate tracking ✅ Day 20 Completed 🚀 Keep going strong with DSA & consistency 💪 #Leetcode #DSA #ProblemSolving #BitManipulation #CodingJourney #InterviewPreparation #Consistency
To view or add a comment, sign in
-
-
🚀 #LeetCode Day Problem Solving 🚀 Day-21 📌 Problem: A robot starts at position (0, 0) on an infinite 2D plane, initially facing North. You are given: An array commands representing movement instructions A list of obstacles on the grid 👉 The robot follows these rules: ✔ -2 → Turn left 90° ✔ -1 → Turn right 90° ✔ 1 to 9 → Move forward k steps (one step at a time) ⚠ If the robot encounters an obstacle, it stops before hitting it and continues with the next command. 👉 Your task is to return the maximum squared Euclidean distance from the origin reached at any point during the movement. 🧠 Example 1: Input: commands = [4, -1, 3], obstacles = [] ✅ Output: 25 📖 Explanation: Move to (0,4) Turn right → face East Move to (3,4) 👉 Max distance = (3² + 4² = 25) 🧠 Example 2: Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]] ✅ Output: 65 📖 Explanation: Obstacle blocks movement at (2,4) Final farthest point = (1,8) 👉 Distance = (1² + 8² = 65) 🧠 Example 3: Input: commands = [6,-1,-1,6], obstacles = [[0,0]] ✅ Output: 36 📖 Explanation: Robot cannot return to origin due to obstacle Farthest point = (0,6) → (6² = 36) 💡 Key Insight: ✔ Use direction vectors: North → (0,1) East → (1,0) South → (0,-1) West → (-1,0) ✔ Store obstacles in a set for O(1) lookup ✔ Move step-by-step to detect obstacles ✔ Track max distance using: x² + y² 📊 Complexity Analysis: ⏱ Time Complexity: O(n + k) (n = commands, k = steps) 📦 Space Complexity: O(obstacles) 🧠 What I Learned: ✔ Simulation with direction handling ✔ Efficient obstacle checking using hashing ✔ Tracking maximum distance dynamically ✅ Day 21 Completed 🚀 Leveling up in Simulation & Grid Problems 💪 #Leetcode #DSA #ProblemSolving #BitManipulation #CodingJourney #InterviewPreparation #Consistency
To view or add a comment, sign in
-
-
#Day30 of DSA Journey | LeetCode 874 - Walking Robot Simulation Today’s problem was all about simulation + direction handling + hashing — a very practical and fun one! Problem Summary: A robot starts at (0,0) facing North and follows a sequence of commands: -2 → Turn Left -1 → Turn Right 1 to 9 → Move forward step-by-step There are obstacles on the grid, and the robot must stop if it encounters one. Goal: Find the maximum squared distance from the origin reached at any point. Key Learnings: Use direction vectors to simplify movement North → (0,1) East → (1,0) South → (0,-1) West → (-1,0) Store obstacles in a HashSet for O(1) lookup Convert (x, y) → string "x,y" or use a pair hash Move step-by-step (not directly k steps!) to handle obstacles correctly Track max distance using: maxDist = max(maxDist, x*x + y*y) Approach: Initialize direction = North Process each command Rotate left/right using modular arithmetic Move step-by-step and stop if obstacle found Update max distance at each step Time Complexity: O(N * K) → N commands, each moving up to K steps Space Complexity: O(M) → for storing obstacles Takeaway: This problem strengthens your understanding of: Simulation problems Direction handling Efficient lookup using hashing #DSA #LeetCode #CodingJourney #JavaScript #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
Day 9/30 – LeetCode Challenge Today’s problem: Walking Robot Simulation II (2069) Problem Overview We are given a grid of size `width × height`. A robot: - starts at position (0, 0) - initially faces East For each step: - it moves forward - if it hits a boundary → it turns 90° counterclockwise and continues We need to design a class that: - moves the robot (step) - returns position (getPos) - returns direction (getDir) Approach At first, this looks like a normal simulation problem, but simulating step-by-step is inefficient The key observation is: - the robot always moves along the boundary - so its path forms a cycle (perimeter) Optimization: - calculate perimeter: perimeter = 2 * (width + height - 2) - reduce steps using: num = num % perimeter Then simulate movement direction-wise: - move as much as possible in current direction - when hitting boundary → change direction Why this works - robot never enters inside → only boundary traversal - movement repeats after one full cycle - modulo helps avoid unnecessary steps Complexity - Time Complexity: O(1) per step call - Space Complexity: O(1) Key Learning Not every simulation needs step-by-step execution. Recognizing patterns like cycles can simplify the solution a lot. #LeetCode #Day9 #DSA #ProblemSolving #CPP #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 37 of 100 Days LeetCode Challenge Problem: Walking Robot Simulation Day 37 builds on previous robot problems with a full simulation + direction handling + hashing challenge 🔥 💡 Key Insight: We simulate movement step-by-step, but: 👉 Need to handle: Direction changes Obstacles Track maximum distance 🔍 Core Approach: 1️⃣ Track Direction Use directions array: North → (0,1) East → (1,0) South → (0,-1) West → (-1,0) 👉 Rotate index: Left → (dir + 3) % 4 Right → (dir + 1) % 4 2️⃣ Store Obstacles Efficiently Use a HashSet for O(1) lookup 3️⃣ Simulate Movement For each step: Move 1 unit at a time If next cell is obstacle → stop movement 4️⃣ Track Maximum Distance At every step: Compute x² + y² Keep max value 🔥 What I Learned Today: Simulation problems require step-by-step precision Hashing is essential for fast obstacle checks Direction handling patterns are reusable 📈 Challenge Progress: Day 37/100 ✅ Consistency unstoppable! LeetCode, Simulation, Hashing, Matrix, Direction Handling, Arrays, DSA Practice, Coding Challenge, Problem Solving #100DaysOfCode #LeetCode #DSA #CodingChallenge #Simulation #Hashing #ProblemSolving #TechJourney #ProgrammerLife #SoftwareDeveloper #CodingLife #LearnToCode #Developers #Consistency #GrowthMindset #InterviewPrep
To view or add a comment, sign in
-
-
LeetCode Daily | Day 71 🔥 LeetCode POTD – 2069. Walking Robot Simulation II (Medium) ✨ 📌 Problem Insight Given a robot on a bounded grid: ✔ Starts at (0, 0), facing East ✔ Moves along grid edges ✔ Turns counter-clockwise when hitting boundary ✔ Need to track position + direction after steps 🔍 Initial Thinking – Simulation ❌ 💡 Idea: ✔ Move step-by-step ✔ Handle boundary checks ✔ Update direction dynamically ⏱ Problem: ❌ Can be inefficient for large steps ❌ Too many edge cases 💡 Optimized Approach – Boundary Precomputation 🔥 👉 Key Idea: ✔ Robot always moves on rectangle boundary ✔ Precompute full path once ✔ Store: • All boundary positions • Direction at each step ✔ Then movement becomes: • idx = (idx + steps) % cycle ⚡ Why this is powerful ✔ Converts simulation → array indexing ✔ No step-by-step movement needed ✔ Handles edge cases automatically ⏱ Complexity: ✔ Precompute: O(perimeter) (~400 max) ✔ step(): O(1) ✅ ✔ getPos / getDir: O(1) 🧠 Key Learning ✔ Identify cycle / pattern in problems ✔ Precomputation can eliminate simulation ✔ Mapping states → indices simplifies logic ✔ Small trick (dir[0] = South) handles full-cycle edge case 🚀 Takeaway A great example of turning a simulation problem into a math/indexing problem — very useful for interviews ⚡ #LeetCode #DSA #Algorithms #CPlusPlus #ProblemSolving #CodingJourney #DataStructures
To view or add a comment, sign in
-
-
LeetCode Daily | Day 70 🔥 LeetCode POTD – 874. Walking Robot Simulation (Medium) ✨ 📌 Problem Insight Given a robot on an infinite grid: ✔ Starts at (0, 0), facing North ✔ Commands include: • -2 → turn left • -1 → turn right • k → move forward k steps ✔ Obstacles block movement ✔ Find max distance² from origin reached 🔍 Initial Thinking – Simulation + Directions ✔ 💡 Idea: ✔ Maintain current position (x, y) ✔ Track direction using index (N, E, S, W) ✔ Use dx, dy arrays for movement ✔ Store obstacles in a set for fast lookup ✔ Move step-by-step (important!) • Before each step → check obstacle • If blocked → stop current command ⏱ Complexity: O(n + steps), Space: O(n) ✔ Efficient due to hashing ✔ Each move handled once 💡 Key Optimization – Hashing Obstacles 🔥 👉 Use set / unordered_set ✔ O(1) obstacle check ✔ Encode (x, y) → faster lookup possible 🧠 Key Learning ✔ Simulation problems need careful handling of edge cases ✔ Direction control using modulo is very useful ✔ Step-by-step movement avoids logical bugs ✔ Hashing turns brute-force into efficient solution A great mix of simulation + hashing — classic interview pattern ⚡ #LeetCode #DSA #Algorithms #CPlusPlus #ProblemSolving #CodingJourney #DataStructures
To view or add a comment, sign in
-
-
🚀 Day 57/100 — Navigating Infinite Planes with Obstacles! Today’s Problem: 874. Walking Robot Simulation 🔹 The Goal: Today was about simulating a robot navigating an infinite XY-plane. Given a series of commands to turn or move forward, the robot must avoid specific obstacle coordinates. The objective: find the maximum squared Euclidean distance the robot reaches during its entire journey. 🔹 The Insight: This problem is a masterclass in Search Space Optimization. While a naive approach might check every step against an array of obstacles—leading to O(K \cdot O) complexity—the real way to win is using a HashSet. By hashing obstacle coordinates into strings like "x,y", we turn an expensive search into a lightning-fast O(1) lookup. 🔹 The Logic: Modular Vector Rotation: I used a 4-direction array and the modulo operator to handle 90-degree turns seamlessly without complex if-else chains. Incremental Verification: Instead of "jumping" to the final position, the robot moves one unit at a time. This ensures we detect an obstacle the very moment the robot hits it. Global Peak Tracking: Monitored the squared distance (x^2 + y^2) at every single valid step to ensure the absolute maximum displacement was recorded. ✨ Achievement: Day 57! Moving past the halfway mark by tackling high-performance simulations. It’s a great reminder that even simple movements require rigorous logic and optimized data structures to scale effectively. 🔍 Steps followed: ✔ Set-Based Lookups: Converted the obstacle grid into a HashSet for constant-time collision detection. ✔ Directional Mapping: Managed 2D movement using index-based vector arrays. ✔ Precision Simulation: Implemented step-by-step movement to respect boundary constraints. 🔧 The Stats: Time Complexity: O(N + K) (where N is commands and K is total steps) Space Complexity: O(O) (to store O obstacles) 57 days down, 43 to go. The logic is getting sharper every single day. Let's keep the momentum! 🛠️ #Java #DSA #LeetCode #CodingJourney #100DaysOfCode #SoftwareEngineer #InternshipBound #Programming #Simulation #GraphTheory #Algorithms #Optimization #Day57
To view or add a comment, sign in
-
-
Day 97: Boundary Logic 🤖🔄 Problem 2069: Walking Robot Simulation II After yesterday’s obstacle course, today’s robot was confined to the perimeter of a grid. While it sounds simpler, the tricky part was handling the orientation and large step counts efficiently. The Strategy: • Modular Optimization: Since the robot only moves along the boundary, any movement greater than the perimeter length is redundant. I calculated the total perimeter as 2⋅w+2⋅(h−2) and used num %= total to skip unnecessary laps. • The "Zero" Edge Case: A key trick here is the orientation at (0,0). If the robot completes a full lap and ends back at the start, its direction must face "South" per the specific rotation rules, not the initial "East." • Simulated Bounds: I used a while loop to process steps side-by-side. For each direction, the robot moves as far as possible until it hits a corner, then rotates counter-clockwise and continues with the remaining steps. • State Management: By maintaining x, y, and dir as class members, I ensured the getPos() and getDir() methods stay O(1). Handling cyclic movement is always about finding the pattern and isolating the edge cases. 97 days down, keeping the streak alive. 🚀 #LeetCode #Java #ObjectOrientedProgramming #Simulation #Algorithms #DailyCode
To view or add a comment, sign in
-
-
Day 7/30 – LeetCode Challenge Today’s problem: Robot Return to Origin (657) Problem Overview A robot starts from the origin (0, 0) and moves according to the given string. Each character represents a move: - 'U' → up - 'D' → down - 'L' → left - 'R' → right We need to determine whether the robot comes back to the origin after completing all the moves. Approach I solved this using simple simulation. - maintain `x` for left/right movement - maintain `y` for up/down movement - update the coordinates for each move Finally: - if both x and y become 0, the robot has returned to the origin - otherwise, it has not Why this works For the robot to return to the starting point: - upward and downward moves must balance - left and right moves must balance So checking the final coordinates is enough. Complexitys - Time Complexity: O(n) - Space Complexity: O(1) Key Learning Not every problem needs an advanced approach. Some problems are just about clean observation and correct simulation. #LeetCode #Day7 #DSA #ProblemSolving #CPP #CodingJourney
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development