Robot Bounded in Circle - Math & Geometry - Leetcode 1041 - Python

  Рет қаралды 40,019

NeetCode

NeetCode

Күн бұрын

🚀 neetcode.io/ - A better way to prepare for Coding Interviews
🐦 Twitter: / neetcode1
🥷 Discord: / discord
🐮 Support the channel: / neetcode
Twitter: / neetcode1
Discord: / discord
⭐ BLIND-75 PLAYLIST: • Two Sum - Leetcode 1 -...
💡 CODING SOLUTIONS: • Coding Interview Solut...
💡 DYNAMIC PROGRAMMING PLAYLIST: • House Robber - Leetco...
🌲 TREE PLAYLIST: • Invert Binary Tree - D...
💡 GRAPH PLAYLIST: • Course Schedule - Grap...
💡 BACKTRACKING PLAYLIST: • Word Search - Backtrac...
💡 LINKED LIST PLAYLIST: • Reverse Linked List - ...
💡 BINARY SEARCH PLAYLIST: • Binary Search
Problem Link: leetcode.com/problems/robot-b...
0:00 - Read the problem
1:59 - Drawing Explanation
9:34 - Coding Explanation
leetcode 1041
This question was identified as an amazon coding interview question from here: github.com/xizhengszhang/Leet...
#amazon #coding #interview
Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.

Пікірлер: 92
@jonaskhanwald566
@jonaskhanwald566 3 жыл бұрын
Where were u these days. Happy to see you back. The day u posted ur last video, I got placed. I wanted to tell u this. Once I was a zero in coding. Ur videos motivated me to code. Thank you Neetcode.
@NeetCode
@NeetCode 3 жыл бұрын
That's awesome news, I'm happy to hear it! Your hard work paid off, congrats! :)
@DanhWasHere
@DanhWasHere 3 жыл бұрын
Cleanest solution to the problem I have seen. Definitely helps that you explained the thinking process instead of us having to glean the reasoning behind some of the conditional checks in the for loop.
@ljduke12manster
@ljduke12manster 2 жыл бұрын
Great Job! To be fair, you don't really need to be that familiar with linear algebra. The way I have always thought about it esp. during middle school is to use the coordinate plane. Draw a coordinate plane and label it appropriately with -x , +x, -y, and +y (We will only looking at +x and +y in the end) . Now say you are rotating 90 degree counterclockwise. So -x , +x, -y, and +y will be shifted to the "label" which is to their immediate left. That is, -x shifts 90 counterclockwise to become -y; -y shifts similarly to become +x; +x shifts to become +y; and +y shifts to become -x. Now, if you read your + x and +y axes, you have new labels which are -y and x respectively. In essence, you have rotated the entire plane by 90 degree counterclockwise. This works for every angle for which there is a utility in performing this exercise.
@abantikatonny
@abantikatonny Жыл бұрын
Thank you. I could not understand the linear algebra thing.
@wendy-wej
@wendy-wej 9 ай бұрын
Thanks so much for this!
@ljduke12manster
@ljduke12manster 9 ай бұрын
You’re welcome guys! The easiest approaches are always better than the esoteric ones. People can do programming without linear algebra. I’m considering starting a KZbin channel to teach programming, starting with C and then transitioning gently to C++.
@Bill-qk6oq
@Bill-qk6oq 3 жыл бұрын
Best Leetcode videos on the internet
@irarose3536
@irarose3536 3 жыл бұрын
Thank you for all the solved problems and clear explanations :)
@tkoiop3242
@tkoiop3242 3 жыл бұрын
Was waiting for some time, thank you for all the effort you put in! Motivates a ton!
@linwingho1787
@linwingho1787 3 жыл бұрын
man, you won't believe how much I like your videos. I literally just attempt a question only if you have made a video on it. Thanks bro, I wish youtube had more good channels like this!
@mubshali7489
@mubshali7489 3 жыл бұрын
Saaaame
@mailsiraj
@mailsiraj 8 ай бұрын
what an elegant code and what a profound thought process - after struggling to understand the mathematical intuition and finally getting the intuition, I watched your code and I am taken aback by the simplicity of the thought process - thank you so much for sharing it.
@mikemihay
@mikemihay 3 жыл бұрын
Thank you for the effort to make this videos!
@nikhildinesan5259
@nikhildinesan5259 3 жыл бұрын
Happy to see you back !!! was waiting for your videos....
@jx7433
@jx7433 2 жыл бұрын
Thank you for the explaination! Although I still have one question after going through the video s few times, I wonder why it is guaranteed to be a cycle if the direction changes after one iteration over the instructions? Is it not possible that even if the direction changed but in the end it could never go back to the posistion (0,0)? Would highly appreciate if someone could help me with my confusion! Thanks in advance!
@anuragchakraborty7607
@anuragchakraborty7607 2 жыл бұрын
No , while executing one instruction set if the final direction changes from the initial one so it means that for every instruction set the direction is gonna change , so as we have only limited number of directions (only 4) , it is inevitable that the robot will move to its initial position once .
@B3Band
@B3Band Жыл бұрын
He showed you multiple examples, but just try to imagine it for yourself. If the net direction change is just one turn, then in loop 3, the robot is now undoing everything it already did in loop 1. And then loop 4 will undo loop 2, so you're back at the start. Remember that if there is only one turn, After the 2nd loop the robot is now facing the opposite direction from the beginning, so it will start undoing it's actions since the forward distance is the same every time.
@chenzhuo9
@chenzhuo9 3 жыл бұрын
NEW COLLECTION! Thanks!!
@MrPhilippos96
@MrPhilippos96 Жыл бұрын
For anyone having trouble with the direction thing : Take a vector (x,y) and note that the vector (-y,x) is perpendicular since their inner product is zero : -xy+yx = 0. But also (y,-x) is perpendicular since inner product is xy-yx=0. Left rotation means that your new vector points to the left and so its x coordinate decreases when walking to that direction and thus the - sign.
@akshaychavan5511
@akshaychavan5511 7 ай бұрын
This is what I came up with in my first try without looking any hints [Beats 98%]: def isRobotBounded(self, instructions: str) -> bool: pos = [0,0] direction = 'N' directions = ['N', 'E', 'S', 'W'] for t in range(4): for i in range(len(instructions)): if instructions[i] == 'G': if direction == 'N': pos[1]+=1 elif direction == 'W': pos[0]-=1 elif direction == 'S': pos[1]-=1 elif direction == 'E': pos[0]+=1 elif instructions[i] == 'L': index = directions.index(direction) direction = directions[(index+3)%4] elif instructions[i] == 'R': index = directions.index(direction) direction = directions[(index+1)%4] if pos == [0,0] and i == len(instructions)-1: return True return False
@anujapuranik2000
@anujapuranik2000 9 ай бұрын
Thankyou again for all your videos and amazing explanation. This is the easiest explanation I ever saw to this problem!!
@algorithmo134
@algorithmo134 3 жыл бұрын
Finally! Hope you are doing well and alright! :D
@susmi51910
@susmi51910 3 жыл бұрын
I swear, if I get a job, it will be only because of NeetCode's incredible explanation!
@mostinho7
@mostinho7 Жыл бұрын
Did it work
@coffeebytes3257
@coffeebytes3257 9 ай бұрын
bro u gotta update us
@mostinho7
@mostinho7 Жыл бұрын
Watched thanks Idea is that if after applying the moves once, the robot is back at the origin then definitely stuck on a loop. If the robot is not at origin but the direction changed from the initial direction then the robot will be in a loop when we apply the instructions infinitely. We return (x,y) == (0,0) || directionChanged after applying the instructions once
@rishmithahahaha
@rishmithahahaha 2 жыл бұрын
Can somebody explain the math behind or post the link where somebody has explained? Everything is clear except the last 2 if cases. Cannot understand the Math behind or how you've arrived at those formulae.
@Neethirajan85
@Neethirajan85 2 жыл бұрын
Case 1 : initially the robot was at (0, 0) position. if the final position (after executing all commands) is also (0, 0) means, it can't go out of bound even after infinite loops. Case 2 : Assume the robot moved from the top end of "L" to the bottom right side of “L", it's direction got changee. So after 4 times executing the same commands it will reach the top end of "L", completing a square. So it can't go out of bound if the direction got changed.
@mohdziaalkhair9148
@mohdziaalkhair9148 2 жыл бұрын
The rule for a rotation by 90° about the origin is (x,y)→(−y,x)
@B3Band
@B3Band Жыл бұрын
Only applies to the left turn
@ahmadaskar3360
@ahmadaskar3360 2 ай бұрын
how to deduce that changing direction in any position whether south, west, east is going to end up a circle , is there a mathematical proof behind this?
@soumodiptajana9001
@soumodiptajana9001 Ай бұрын
You are awesome... Thank you man...
@mirceanicolaescu9804
@mirceanicolaescu9804 2 жыл бұрын
Great explanation! I have a small doubt about the rotation. On the left rotation, it seems to me we only change sign when we switch from the Oy to Ox. Let's say we are in the initial position, facing north - encoded (0,1). If we rotate left, we will be facing west - encoded (-1,0). So far so good. If we do another left rotation, we will be facing south - encoded (0,-1) => we did not change sign!!! Essentially we change signs only when we go from N to W and S to E. The other two, W to S and E to N, do not change signs! Am I missing something here?
@jieli8
@jieli8 2 жыл бұрын
I agree with you, i think the rotation has a bug in the code
@cocoatut49
@cocoatut49 Жыл бұрын
what do you mean when you say we did not change sign
@EIKA.
@EIKA. Жыл бұрын
we are facing west i.e (-1,0). So if we rotate left again, first we need to swap values so it would be (0,-1). Next would be to put negative sign on X parameter. Since 0 cant be negative its zero only. so south would be (0,-1)
@B3Band
@B3Band Жыл бұрын
It still works. In the other two directions, the the y coordinate is zero, so when you make x into -y, it becomes -0, which is still 0. No issues at all with the code.
@brucebatmanwayne8514
@brucebatmanwayne8514 Жыл бұрын
9:35 how did your application at freddie mac go? :p
@NeetCode
@NeetCode Жыл бұрын
😳
@infiniteloop5449
@infiniteloop5449 Жыл бұрын
@@NeetCode lmao!
@ZackOfAllTrad3s
@ZackOfAllTrad3s 3 жыл бұрын
Another great video!! I'm really having trouble following the python specific syntax sugar though. (dirX, dirY) != (0, 1) , is this read as (dirX != 0 && dirY != 1) or is it read as (dirX != 0 || dirY != 1), I would love a more non-pythony way of doing things so non pythoners can keep up, thanks!!
@okeyD90232
@okeyD90232 2 жыл бұрын
java solution: public boolean isRobotBounded(String instructions) { int[] dir = new int[]{1,0}; int[] pos = new int[]{0,0}; char ch[] = instructions.toCharArray(); for(char c : ch){ if(c=='G'){ pos[0]+=dir[0]; pos[1]+=dir[1]; }else if(c=='L'){ int temp = dir[0]; dir[0] = -1*dir[1]; dir[1] = temp; }else{ int temp = dir[1]; dir[1] = -1*dir[0]; dir[0] = temp; } } return (pos[0]==0&&pos[1]==0) || (dir[0]!=1 || dir[1]!=0); }
@tusharvyavahare9229
@tusharvyavahare9229 Жыл бұрын
It should be (x==0&&y==0)||(dirX!=0||dirY!=1). Suppose, A=(dirX,dirY), B=(0,1). So it's checking whether A!=B
@1234567pinkgirl
@1234567pinkgirl 2 жыл бұрын
its showing wrong on leet code if i type exactly same code that you have here..
@NeetCode
@NeetCode 2 жыл бұрын
Just ran the same code and it works, pasted it below, let me know if it still gives error: class Solution: def isRobotBounded(self, instructions: str) -> bool: dirX, dirY = 0, 1 x, y = 0, 0 for d in instructions: if d == "G": x, y = x + dirX, y + dirY elif d == "L": dirX, dirY = -1*dirY, dirX else: dirX, dirY = dirY, -1*dirX return (x, y) == (0, 0) or (dirX, dirY) != (0, 1)
@infiniteloop5449
@infiniteloop5449 Жыл бұрын
To think about which direction the robot is rotating, you can simply think about the 4 quadrant signs of quadrants I-IV learned in middle school algebra.
@MANOJKUMAR-mb2uw
@MANOJKUMAR-mb2uw Жыл бұрын
I wonder is there any way that makes a path spiral then what will be the case it will be return true by ur code because it will change direction but i don't think it is a circular
@mattstrayer1863
@mattstrayer1863 Жыл бұрын
Try as you might, the robot will return to its starting position if the final direction is south, east or west. For example, if after the first round the robot ends up at (x + a, y + b) and facing east, then in the next iterations it will end up at (x + a + b, y + b − a) → (x + b, y − a) → (x, y), back where it started! Since the choice of the displacement (a, b) was arbitrary, this always happens. You can convince yourself of the other directions (facing south and west) similarly.
@iarpanbose
@iarpanbose 3 жыл бұрын
I didn't get the point where initially dirx, diry=0,1 where as im standing at 0,0
@minirasamedova648
@minirasamedova648 3 жыл бұрын
It's not a position, it's a direction that robot is facing initially. Since robot facing North, then the direction is (0, 1) the initial position is x, y = 0, 0
@CS_n00b
@CS_n00b Ай бұрын
I find it hard to prove to myself that if we are in a new posn with a different direction we will always end up at the origin
@Akaash449
@Akaash449 2 жыл бұрын
I've seen that if there is no L on the string, robot goes on unidirectionally indefinitely, but even if there is one L, the robot eventually gets stuck in an infinite loop if the robot is instructed to move on infinitely.
@tcal208
@tcal208 2 жыл бұрын
"RG" -> no L still in a loop. "GLGRG" -> L but robot is never stuck in an infinite loop.
@Akaash449
@Akaash449 2 жыл бұрын
@@tcal208 no it says G makes it go 1 unit only
@tcal208
@tcal208 2 жыл бұрын
@@Akaash449 but the robot repeats it for ever, I don't get your point either way
@Akaash449
@Akaash449 2 жыл бұрын
@@tcal208 no I think the robot doesn't repeat the forward instruction only. After RG it will execute another RG and go right and 1 unit forward, and keep on repeating RG until a unit size square is formed thus satisfying the break condition.
@tcal208
@tcal208 2 жыл бұрын
@@Akaash449 Which means, the robot is bound to a circle in the plane, thus the "no L but still in a loop".
@neeldesai108
@neeldesai108 2 жыл бұрын
Surprisingly same Java code fails on leetcode. Following is my code snippet that's failing on LettCode. class Solution { public boolean isRobotBounded(String instructions) { // Initially we are facing to North int dirX = 0, dirY = 1; // We start at origin int x = 0, y = 0; for (char ch : instructions.toCharArray()) { if (ch == 'G') { x = x + dirX; y = y + dirY; } else if (ch == 'L') { int temp = dirX; dirX = -dirY; dirY = temp; } else{ int temp = dirX; dirX = dirY; dirY = -temp; } } // after one cycle: // robot returns into initial position // or robot has changed direction return (x == 0 && y == 0) || (dirX !=0 && dirY != 1); } }
@Neethirajan85
@Neethirajan85 2 жыл бұрын
return (x == 0 && y == 0) || (dirX != 0 || dirY != 1) ;
@rams2478
@rams2478 2 жыл бұрын
same here.. failing in Java, any fixes?
@MsQmonkey
@MsQmonkey 2 жыл бұрын
if ((x==0 && y==0) || dirX != 0 || dirY != 1) return true; else return false;
@dmitrytsyrulik5337
@dmitrytsyrulik5337 Жыл бұрын
return (x==0 && y==0) || dirX != 0 || dirY != 1;
@MKhan-eq6pj
@MKhan-eq6pj 3 жыл бұрын
Can someone please explain the logic behind his two conditions: 1) change in position, if position didn't change. 2) change in direction , if position did change and direction change. if one of those conditions is true, then we have a cycle. How :
@siqb
@siqb 3 жыл бұрын
1) Well if you come back to the same position after a single run i.e. back to the origin that means no matter what direction you are facing before each run, you will always end up back at the origin. You can think of it as a closed-loop circuit that always ends up where you start (no matter the direction because if its true for north, no reason why it would not be equally true for east, west or south). 2) This says that after one run, if your direction is not north (which is always our starting direction), then you are also in a loop. If you end up facing south, then the loop size is 2 (i.e. you will be back at the origin after 2 runs). If you end up facing left or right, then the loop size is 4. Anybody who has driven without Maps in a new area knows this :D Both of these were not obvious to me frankly. I always felt uncertain that there might be edge cases I am not thinking about. In fact being sure of this is the trickiest part of this question for me.
@JM25Jey
@JM25Jey 3 жыл бұрын
@@siqb I JUST started this problem so maybe I haven't beat my head up against it enough to understand what's going on. But let's say that you have a test case in which you have directions like "LGRG" OR "RGLG" (that fits both criteria to return true according to this video and what you just stated). If you mapped that out on a 2D plane, it definitely doesn't stay within a finite circle if it runs infinitely. A loop? Sure. But not within a circle
@JM25Jey
@JM25Jey 3 жыл бұрын
LMAO nevermind, I just re-read the part in the second condition that specifies "not facing north" at the end of the loop. Makes sense now
@MKhan-eq6pj
@MKhan-eq6pj 3 жыл бұрын
@@siqb thank you man.
@B3Band
@B3Band Жыл бұрын
The first condition is needed because supposed you have GG LL GG LL After 4 Left turns, you are facing north. And according toe condition 2, facing north at the end means you move forward forever (no loop). So you need to first check if you actually just end up at (0,0) at the start of every loop. Then it won't matter that you're facing north. However, if you end up anywhere else, then facing north at the end means you never come back to the start, and not facing north means you will come back in either 2 or 4 loops.
@amitupadhyay6511
@amitupadhyay6511 3 жыл бұрын
Could u please solve 725. Split Linked List in Parts?
@onepercentbetter3313
@onepercentbetter3313 2 жыл бұрын
Don't you have Java solutions pls
@Neethirajan85
@Neethirajan85 2 жыл бұрын
Check in below comments.
@onepercentbetter3313
@onepercentbetter3313 2 жыл бұрын
@@Neethirajan85 where?
@Neethirajan85
@Neethirajan85 2 жыл бұрын
@@onepercentbetter3313 class Solution { public boolean isRobotBounded(String instructions) { int dirX = 0; int dirY = 1; int x=0; int y=0; for (char c : instructions.toCharArray()) { if (c=='G') { x = x + dirX; y = y + dirY; } else if (c=='L') { int temp = dirX; dirX = -1 * dirY; dirY = temp; } else { int temp = dirX; dirX = dirY; dirY = -1 * temp; } } return (x == 0 && y == 0) || (dirX != 0 || dirY != 1) ; } }
@ygwg6145
@ygwg6145 Жыл бұрын
The solution using the inherent periodic nature by running the command string 4 times is cleaner and more intuitive.
@B3Band
@B3Band Жыл бұрын
And takes longer. And shows a lack of optimization skills. The hiring manager won't like that. They'll have to worry that every time you get a task, you might brute force with O(n^2) or O(n!) solutions because you feel it's more intuitive. Software engineers get paid to engineer.
@maniyadav3256
@maniyadav3256 2 жыл бұрын
Please someone clear my doubt that , in interview do we have to write the code from main function or only the function . Please @NeetCode or @ anyone
@Neethirajan85
@Neethirajan85 2 жыл бұрын
Most of the interviewer expects only the function.
@ashwinvarma9349
@ashwinvarma9349 Жыл бұрын
whats wrong in this c++ code: bool isRobotBounded(string instructions) { int dirX = 0, dirY = 1; int x = 0, y = 0; for(char ch: instructions){ if(ch == 'G'){ x = x + dirX; y = y + dirY; } else if(ch == 'L'){ char temp = dirX; dirX = -1 * dirY; dirY = temp; } else{ char temp = dirX; dirX = dirY; dirY = -1 * temp; } } return ((x == 0) && (y == 0)) || ((dirX != 0) && (dirY != 1)); }
@aseemsameer7281
@aseemsameer7281 2 жыл бұрын
Brother, It's not so challenging to look at the hints and answer. Can you explain exactly why does change in direction conclude that the pattern will create a circle? In the interviews, such hints will not be given.
@vinayak186f3
@vinayak186f3 3 жыл бұрын
It's so disheartening to see just 1 like in 20 hours ,I request all to please atleast leave a like , a like doesn't cost anything , but someone's efforts does .
Python for Coding Interviews - Everything you need to Know
26:18
Search a 2D Matrix - Leetcode 74 - Python
10:59
NeetCode
Рет қаралды 146 М.
Llegó al techo 😱
00:37
Juan De Dios Pantoja
Рет қаралды 36 МЛН
Longest Repeating Character Replacement - Leetcode 424 - Python
20:44
Factory Method Pattern - Design Patterns (ep 4)
27:21
Christopher Okhravi
Рет қаралды 539 М.
Stone Game II - Leetcode 1140 - Python
18:40
NeetCodeIO
Рет қаралды 11 М.
How Bugatti's New Electric Motor Bends Physics
9:25
Ziroth
Рет қаралды 72 М.
The Josephus Problem - Numberphile
13:58
Numberphile
Рет қаралды 7 МЛН
Pytest Tutorial - How to Test Python Code
1:28:39
freeCodeCamp.org
Рет қаралды 173 М.
Robot Bounded In Circle 🔥| Leetcode 1041 | Math | String
18:02
Ayushi Sharma
Рет қаралды 3,7 М.
Как бесплатно замутить iphone 15 pro max
0:59
ЖЕЛЕЗНЫЙ КОРОЛЬ
Рет қаралды 1,3 МЛН
Как распознать поддельный iPhone
0:44
PEREKUPILO
Рет қаралды 2,1 МЛН
Samsung laughing on iPhone #techbyakram
0:12
Tech by Akram
Рет қаралды 680 М.
1$ vs 500$ ВИРТУАЛЬНАЯ РЕАЛЬНОСТЬ !
23:20
GoldenBurst
Рет қаралды 1,8 МЛН
S24 Ultra and IPhone 14 Pro Max telephoto shooting comparison #shorts
0:15
Photographer Army
Рет қаралды 9 МЛН